Skip to content

Instantly share code, notes, and snippets.

@skapil
Forked from durden/callable.py
Last active April 17, 2018 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skapil/9407f3d3f548d4089799c9488f86b3bf to your computer and use it in GitHub Desktop.
Save skapil/9407f3d3f548d4089799c9488f86b3bf to your computer and use it in GitHub Desktop.
Clever way to use Python __call__ and __getattr__ to create web APIs that can map directly (dynamically) to actual API
class MyCallable(object):
def __init__(self, urlparts, callable):
self.urlparts = urlparts
self.callable = callable
def __call__(self, **kwargs):
print kwargs
print self.urlparts
def __getattr__(self, name):
# Return a callable object of this same type so that you can just keep
# chaining together calls and just adding that missing attribute to the
# arguments
return self.callable(self.urlparts + name, self.callable)
class Service(MyCallable):
pass
x = Service('a', MyCallable)
x.path.path1()
x.path.path1.path2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment