Created
May 4, 2016 07:09
-
-
Save oakfang/0c647ee7ceab3917e67228e8dcc38845 to your computer and use it in GitHub Desktop.
Add an unbound method to a class (Python 2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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