Skip to content

Instantly share code, notes, and snippets.

@1st1
Created January 31, 2017 19:06
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 1st1/ebee935256c7cc35c38cc3f73f00461d to your computer and use it in GitHub Desktop.
Save 1st1/ebee935256c7cc35c38cc3f73f00461d to your computer and use it in GitHub Desktop.
autosuper
class autosuper:
_is_bound = object()
def __init__(self, meth):
self.__meth = meth
def __call(meth, inst, owner, args, kwargs):
if inst is autosuper._is_bound:
result = meth(*args, **kwargs)
else:
result = meth(inst, *args, **kwargs)
supermeth = None
for cls in owner.__mro__[1:]:
if meth.__name__ in cls.__dict__:
supermeth = getattr(cls, meth.__name__)
break
if supermeth is not None:
if inst is autosuper._is_bound:
supermeth(*args, **kwargs)
else:
supermeth(inst, *args, **kwargs)
return result
def __get__(self, inst, owner):
if inst is None:
inst = autosuper._is_bound
return (lambda *args, **kwargs:
autosuper.__call(self.__meth, inst, owner, args, kwargs))
class Base:
@autosuper
def say(self):
print(self, 'BASE')
class A(Base):
@autosuper
def say(self):
print(self, 'A')
class B(A):
@autosuper
def say(self):
print(self, 'B')
B().say()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment