Created
November 2, 2010 04:16
-
-
Save ryanmcgrath/659255 to your computer and use it in GitHub Desktop.
Emulating Ruby's "method_missing" in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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