Skip to content

Instantly share code, notes, and snippets.

@ohe
Created September 28, 2016 14:24
Show Gist options
  • Select an option

  • Save ohe/e0676cf2502bcc71a67e4a44ed141a96 to your computer and use it in GitHub Desktop.

Select an option

Save ohe/e0676cf2502bcc71a67e4a44ed141a96 to your computer and use it in GitHub Desktop.
Given an object and a function, install the function as an instance method.
def redefine_instance_fn(obj, ext_fn, remote_name=None):
"""
Given an object and a function, install the function as an instance method.
Overrides any existing instance method with the same name.
Preserves object identity.
Uses name of function by default.
Note: not a best practice, but sometimes necessary.
>>> class A:
... def __init__(self, val):
... self.val = val
... def f(self, x):
... print self.val + str(x)
>>> a = A('sdfs')
>>> obj_id = id(a)
>>> a.f(3)
sdfs3
>>> def f(self, x):
... print self.val + str(x + 2)
>>> def g(self, x):
... print self.val + str(x + 1)
>>> redefine_instance_fn(a, g, 'f')
>>> obj_id == id(a)
True
>>> a.f(3)
sdfs4
>>> redefine_instance_fn(a, f, 'f')
>>> obj_id == id(a)
True
>>> a.f(3)
sdfs5
"""
if remote_name is None:
remote_name = ext_fn.__name__
ft = type(getattr(obj, remote_name))
setattr(obj, remote_name, ft(ext_fn, obj, obj.__class__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment