Skip to content

Instantly share code, notes, and snippets.

@floer32
Created February 11, 2015 01:42
Show Gist options
  • Save floer32/a928b801ca5c7705e94e to your computer and use it in GitHub Desktop.
Save floer32/a928b801ca5c7705e94e to your computer and use it in GitHub Desktop.

Revisions

  1. floer32 created this gist Feb 11, 2015.
    26 changes: 26 additions & 0 deletions python_bind_function_as_method.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    # based on: http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method#comment8431145_1015405
    def bind(instance, func, as_name):
    """ Turn a function to a bound method on an instance
    .. doctest::
    >>> class Foo(object):
    ... def __init__(self, x, y):
    ... self.x = x
    ... self.y = y
    >>> foo = Foo(2, 3)
    >>> my_unbound_method = lambda self: self.x * self.y
    >>> bind(foo, my_unbound_method, 'multiply')
    >>> # noinspection PyUnresolvedReferences
    ... foo.multiply()
    6
    :param instance: some object
    :param func: unbound method (i.e. a function that takes `self` argument, that you now
    want to be bound to this class as a method)
    :param as_name: name of the method to create on the object
    SIDE EFFECTS:
    - creates the new bound method on this instance, like you asked for
    """
    setattr(instance, as_name, func.__get__(instance, instance.__class__))