Skip to content

Instantly share code, notes, and snippets.

@ryanmcgrath
Created November 2, 2010 04:16
Show Gist options
  • Save ryanmcgrath/659255 to your computer and use it in GitHub Desktop.
Save ryanmcgrath/659255 to your computer and use it in GitHub Desktop.
Emulating Ruby's "method_missing" in Python.
method_dictionary = {
"getPublicTimeline": {
"endpoint": "http://...",
},
}
class Twython(object):
def __init__(self, params):
"""
Store params and junk. Ordinarily more verbose.
"""
self.params = params
def __getattr__(self, method_name):
"""
This is called every time a class method or property
is checked and/or called.
In here we'll return a new function to handle what we
want to do.
"""
def get(self, **kwargs):
# Make our API calls, return data, etc
if method_name in method_dictionary:
return get.__get__(self)
else:
# If the method isn't in our dictionary, act normal.
raise AttributeError, method_name
# Instantiate...
twitter = Twython()
# Call an arbitrary method.
twitter.getPublicTimeline()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment