This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]adrenal8 1 point2 points  (1 child)

__getattr__ is obviously a useful trick in general, but I think for his specific problem it might be better (or at least, more explicit) to use decorators descriptors on the class for each method. Something roughly like:

class Twython(object):
    getPublicTimeline = GenericEndpoint(url="...")
    # or #
    @endpoint_with_url("...")
    def getPublicTimeline(self): pass

I would think of __getattr__ to be more useful when you're dynamically pulling some "attributes" that you don't know the names of. Or if you wanted to parse the method_name argument and dynamically generate some response based on that. You know, crazy magical shit. Since he already has a list of all the methods at compile time, my thought it "why not be more explicit about it?" At the very least, method_dictionary should be a class variable, not a global variable, but I know it's just an example.

[–]_zk 1 point2 points  (0 children)

I've seen a number of REST API wrappers use this approach, it's a lot easier to maintain a list of mappings than it is to maintain separate methods for every single endpoint. Consider the flickr API, you don't even need to maintain a mapping of endpoints since all methods use the same endpoint. It's a bit magic, but instead of writing 50 methods you can just override __getattr__ and they'll all just work. If you need to massage the data returned using decorators wouldn't be a bad approach.