Python: Bind an Unbound Method?

python methodtype
python add method to imported class
how to get bound method values in python
bind() function in python
python bind function
python 3 unbound method
python bind two functions
python inspect bind example

In Python, is there a way to bind an unbound method without calling it?

I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so:

class MyWidget(wx.Window):
    buttons = [("OK", OnOK),
               ("Cancel", OnCancel)]

    # ...

    def Setup(self):
        for text, handler in MyWidget.buttons:

            # This following line is the problem line.
            b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)

The problem is, since all of the values of handler are unbound methods, my program explodes in a spectacular blaze and I weep.

I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn't find anything. Right now, I'm using functools.partial to work around this, but does anyone know if there's a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it?

All functions are also descriptors, so you can bind them by calling their __get__ method:

bound_handler = handler.__get__(self, MyWidget)

Here's R. Hettinger's excellent guide to descriptors.

As a self-contained example pulled from Keith's comment:

def bind(instance, func, as_name=None):
    Bind the function *func* to *instance*, with either provided name *as_name*
    or the existing name of *func*. The provided *func* should accept the 
    instance as the first argument, i.e. "self".
    if as_name is None:
        as_name = func.__name__
    bound_method = func.__get__(instance, instance.__class__)
    setattr(instance, as_name, bound_method)
    return bound_method

class Thing:
    def __init__(self, val):
        self.val = val

something = Thing(21)

def double(self):
    return 2 * self.val

bind(something, double)
something.double()  # returns 42

Bind Python function as method · GitHub, In general, a descriptor is an object attribute with “binding behavior”, one Properties, bound and unbound methods, static methods, and class  Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below. Bound methods

This can be done cleanly with types.MethodType. Example:

import types

def f(self): print self

class C(object): pass

meth = types.MethodType(f, C(), C) # Bind f to an instance of C
print meth # prints <bound method C.f of <__main__.C object at 0x01255E90>>

Descriptor HowTo Guide, When you call such bound method, it passes the class of a as the first argument. Static methods are even simpler: they don't bind anything at all, and simply return​  If an unbound method means that it is not bound to any specific instance of a class, then Python will not force some_method to accept an object instance, since it doesn’t have one to give.

Creating a closure with self in it will not technically bind the function, but it is an alternative way of solving the same (or very similar) underlying problem. Here's a trivial example:

self.method = (lambda self: lambda args:

Python Language, In Python you sometimes want to dynamically add methods to classes the new method we will need to add an "unbound method" to the class. Python Language Bound, unbound, and static methods. Example. The idea of bound and unbound methods was removed in Python 3. In Python 3 when you declare a method within a class, you are using a def keyword, thus creating a function object. This is a regular function, and the surrounding class works as its namespace.

This will bind self to handler:

bound_handler = lambda *args, **kwargs: handler(self, *args, **kwargs)

This works by passing self as the first argument to the function. object.function() is just syntactic sugar for function(object).

Dynamically Adding a Method to Classes or Class Instances in Python, In Python we have functions and methods. Function definitions in Python look like this: def sloganify(x): return "{} or bust!".format(x). And method  In Python, is there a way to bind an unbound method without calling it? I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so:

Late to the party, but I came here with a similar question: I have a class method and an instance, and want to apply the instance to the method.

At the risk of oversimplifying the OP's question, I ended up doing something less mysterious that may be useful to others who arrive here (caveat: I'm working in Python 3 -- YMMV).

Consider this simple class:

class Foo(object):

    def __init__(self, value):
        self._value = value

    def value(self):
        return self._value

    def set_value(self, value):
        self._value = value

Here's what you can do with it:

>>> meth = Foo.set_value   # the method
>>> a = Foo(12)            # a is an instance with value 12
>>> meth(a, 33)            # apply instance and method
>>> a.value()              # voila - the method was called

Methods and method binding in Python, What's the difference between them? The difference is that Bound Method has one more instance binding process, A.f is unbound method, and  A function is created by the def statement, or by lambda. Under Python 2, when a function appears within the body of a class statement (or is passed to a type class construction call), it is transformed into an unbound method.

Python: Bound Method and Unbound Method, A method can have a special Python-defined name with two leading and two a class is a Python object with arbitrarily named attributes that you can bind and  As of Python 3.0: The concept of “unbound methods” has been removed from the language. When referencing a method as a class attribute, you now get a plain function object. So this example is valid python 3.X code, since there are no "unbound methods" just functions attached to class objects.

Unbound, The normal way to add functionality (methods) to a class in Python is to define Adding the method to an object of type “A” is also possible. can't as the concept of an *unbound* method has disappeared in Python 3 (see:  The only difference from regular functions is that the first argument is reserved for the object instance. By Python convention, the instance reference is called self but may be called this or any other variable name. To support method calls, functions include the __get__() method for binding methods during attribute access. This means that all functions are non-data descriptors which return bound or unbound methods depending whether they are invoked from an object or a class.

Adding methods to Python classes « BRG blog, It also works with modification: change the unbound method and you change all the bound methods. This means you can dynamically adjust a class based on the​  In Python, it is a convention of the language that instance methods are required to consume a special first argument (conventionally called self) that represents the actual instance object from which they will be called.

  • @Christopher - A method that isn't bound to the scope of the object it was sucked from, so you have to pass self explicitly.
  • I particularly like "spectacular blaze and I weep."
  • That's pretty cool. I like how you can omit the type and get back a "bound method ?.f" instead.
  • I like this solution over the MethodType one, because it works the same in py3k, while MethodType's arguments have been changed up a bit.
  • And thus, a function to bind functions to class instances: bind = lambda instance, func, asname: setattr(instance, asname, func.__get__(instance, instance.__class__)) Example: class A: pass; a = A(); bind(a, bind, 'bind')
  • Huh, you learn something new every day. @Kazark In Python 3, at least, you can also skip supplying the type, as __get__ will take that implicitly from the object parameter. I'm not even sure if supplying it does anything, as it makes no difference what type I supply as the second parameter regardless of what the first parameter is an instance of. So bind = lambda instance, func, asname=None: setattr(instance, asname or func.__name__, func.__get__(instance)) should do the trick as well. (Though I'd prefer having bind usable as a decorator, personally, but that's a different matter.)
  • Wow, never knew functions were descriptors. That's a very elegant design, methods are just plain functions in the class' __dict__ and attribute access gives you unbound or bound methods through the normal descriptor protocol. I always assumed it was some sort of magic that happened during type.__new__()
  • +1 This is awesome, but there's no reference to it in the python docs at the URL you provided.
  • +1, I prefer not to have calls to magic functions in my code (i.e. __get__). I don't know for which version of python this you tested this on, but on python 3.4, the MethodType function takes two arguments. The function and the instance. So this should be changed to types.MethodType(f, C()).
  • Here it is! It's a good way to patch instance methods: wgt.flush = types.MethodType(lambda self: None, wgt)
  • It is actually mentioned in the docs, but in the descriptor page from the other answer:
  • Yes, this is about the same as my original fix, which was to use functools.partial(handler, self)
  • Yes, but this calls the method. The problem is I need to be able to pass the bound method as a callable object. I have the unbound method and the instance I'd like it to be bound to, but can't figure out how to put it all together without immediately calling it