Skip to content

Instantly share code, notes, and snippets.

@alexmojaki
Created July 4, 2018 14:26
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 alexmojaki/d3efde4b4d8d2d2b0e9dfe7ca6c32633 to your computer and use it in GitHub Desktop.
Save alexmojaki/d3efde4b4d8d2d2b0e9dfe7ca6c32633 to your computer and use it in GitHub Desktop.
def attr_to_arg(func):
"""
This is stupid and I love it.
Basically instead of calling:
foo("thing", stuff)
You can call:
foo.thing(stuff)
once you apply this decorator to foo.
Works on methods, unless you try using the 'unbound' method.
"""
class AttrGetter:
def __init__(self):
self.instance = None
def __getattr__(self, item):
return Caller(self.instance, item)
def __get__(self, instance, owner):
self.instance = instance
return self
class Caller:
def __init__(self, instance, item):
self.instance = instance
self.item = item
def __call__(self, *args, **kwargs):
if self.instance is None:
return func(self.item, *args, **kwargs)
else:
return func(self.instance, self.item, *args, **kwargs)
return AttrGetter()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment