Skip to content

Instantly share code, notes, and snippets.

@purefunctor
Created June 17, 2020 07:48
Show Gist options
  • Save purefunctor/cd1c40d65ee08345cd51cb6aabd662c1 to your computer and use it in GitHub Desktop.
Save purefunctor/cd1c40d65ee08345cd51cb6aabd662c1 to your computer and use it in GitHub Desktop.
import functools
import types
def attrfunc(func=None, **attrs):
if not func:
return functools.partial(attrfunc, **attrs)
return AttrFunc(func, **attrs)
class AttrFunc:
def __init__(self, func, **attrs):
self.func = func
for k, v in attrs.items():
setattr(self, k, v)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __get__(self, obj, cls):
if obj is None:
return self
return types.MethodType(self, obj)
class Foo:
@attrfunc(foo=5, bar=5)
def hello(self, x, y):
print(x + y)
f = Foo()
print(f"Attribute {f.hello.foo=}")
print(f"Attribute {f.hello.bar=}")
f.hello(5, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment