Skip to content

Instantly share code, notes, and snippets.

@oakfang
Created May 4, 2016 07:09
Show Gist options
  • Save oakfang/0c647ee7ceab3917e67228e8dcc38845 to your computer and use it in GitHub Desktop.
Save oakfang/0c647ee7ceab3917e67228e8dcc38845 to your computer and use it in GitHub Desktop.
Add an unbound method to a class (Python 2)
from types import MethodType
LAMBDA_NAME = '<lambda>'
def extend(cls, method, name=None):
method_name = method.__name__
if method_name == LAMBDA_NAME and name is None:
raise NameError('Please provide a usable name for a lambda method')
elif name is not None:
method_name = name
setattr(cls, method_name, MethodType(method, None, cls))
class X(object):
pass
x = X()
x.meow() # This fails
extend(X, lambda self: 5, 'meow')
x.meow() # returns 5 :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment