Skip to content

Instantly share code, notes, and snippets.

@tritium21
Created April 10, 2015 19:27
Show Gist options
  • Save tritium21/a39174e31569a2383689 to your computer and use it in GitHub Desktop.
Save tritium21/a39174e31569a2383689 to your computer and use it in GitHub Desktop.
"""
Today I learned... How both super and method binding works. /hack
"""
import functools
import types
class Duper(object):
"""
A very simplistic reimplementation of super().
There are numerous limitations on this, but it works.
"""
def __new__(cls, typ, obj):
self = object.__new__(cls)
assert isinstance(obj, typ)
self.__obj = obj
self.__typ = typ
return self
def __getattr__(self, name):
for base in self.__typ.__mro__[1:]:
attr = base.__dict__.get(name, None)
if attr is None:
continue
if isinstance(attr, types.FunctionType):
attr = attr.__get__(self.__obj, base)
return attr
raise AttributeError
class FakeMethod(object):
"""
Knowing what I know now, I can get python to bind instances of my callables
like they are methods. It shocked me this works
"""
def __call__(self, instance):
print "do something", instance
def __get__(self, instance, cls):
return functools.partial(self, instance=instance)
class A(object):
foo = FakeMethod()
@tritium21
Copy link
Author

Next step... do this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment