Skip to content

Instantly share code, notes, and snippets.

@NegativeMjark
Created December 24, 2014 11:03
Show Gist options
  • Save NegativeMjark/b091d650769dc14e6dda to your computer and use it in GitHub Desktop.
Save NegativeMjark/b091d650769dc14e6dda to your computer and use it in GitHub Desktop.
Bind attributes using decorators and meta classes.
def bindto(target):
def set_attr(name, value):
if name == "__new__" and isinstance(target, type):
setattr(target, name, staticmethod(value))
else:
setattr(target, name, value)
def bind_class(cls, name, bases, members):
for key, value in members.items():
set_attr(key, value)
return target
def bind_decorator(cls, thing):
if not hasattr(thing, "__name__") and hasattr(thing, "__func__"):
set_attr(thing.__func__.__name__, thing)
else:
set_attr(thing.__name__, thing)
Bind = type("Bind", (), {"__call__": bind_decorator})()
Bind.__class__.__new__ = staticmethod(bind_class)
return Bind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment