Sub topic 8
How functions become bound methods
This chapter assumes you can write classes with methods and know the difference between instance and class attributes. It also assumes you have met __get__, __set__ and the split between data and non-data descriptors. Here we apply those ideas to the most common descriptor in Python: the plain function.
The puzzle: one function, two behaviors
Define a method and look at it two ways:
class C:
def greet(self):
return "hi"
c = C()
print(C.__dict__["greet"])
print(C.greet)
print(c.greet)The first two lines print a function. The last prints a bound method that remembers c. All three start from the same object, the function stored in C.__dict__. Something converts it during c.greet. That something is the descriptor protocol.
Functions are non-data descriptors
Every function object defines __get__ and does not define __set__ or __delete__. By the rules from the previous chapters, a function in a class is a non-data descriptor. Two consequences follow:
- When you read
c.greet, Python finds the function in the class, sees that it has__get__, and calls it. - Because the function is non-data, an entry named
greetin the instance__dict__wins over it.
You can perform the conversion by hand:
class C:
def greet(self):
return "hi"
c = C()
plain = C.__dict__["greet"]
bound = plain.__get__(c, C)
print(type(plain).__name__) # function
print(type(bound).__name__) # method
print(bound() == c.greet()) # True
print(bound == c.greet) # Truec.greet is shorthand for type(c).__dict__["greet"].__get__(c, type(c)), once the MRO search has found the function.
What `__get__` returns
The function's __get__ behaves like this:
- Called with an instance (
objis notNone), it returns a bound method object that packages the function and the instance. - Called with
obj=None, as happens forC.greet, it returns the function itself.
The second rule is why C.greet is an ordinary function in Python 3. Python 2 returned an "unbound method" here, and that concept no longer exists.
A bound method exposes its two parts:
class C:
def greet(self):
return "hi"
c = C()
m = c.greet
print(m.__self__ is c) # True
print(m.__func__ is C.greet) # True
print(c.greet is c.greet) # False
print(c.greet == c.greet) # TrueEach attribute access builds a new method object, so is fails. Equality compares __self__ by identity and __func__ by equality, so == succeeds. Do not rely on is when comparing bound methods, for example when removing a callback from a list. Use ==.
When you call a bound method, it calls __func__(__self__, *args, **kwargs). That is the whole mechanism behind the self parameter. There is no special syntax for self. It is just the first positional argument, supplied by the method object.
Modeling it in pure Python
You can build the same behavior with your own descriptor and types.MethodType, which creates bound method objects:
import types
class MyFunction:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __get__(self, obj, objtype=None):
if obj is None:
return self
return types.MethodType(self.func, obj)
class Greeter:
@MyFunction
def hello(self, name):
return f"{name}, from {type(self).__name__}"
g = Greeter()
print(g.hello("Ana")) # Ana, from Greeter
print(g.hello.__self__ is g) # True
print(Greeter.hello is Greeter.__dict__["hello"]) # True
print(Greeter.hello(g, "Bo")) # Bo, from GreeterGreeter.hello returns the MyFunction object, and calling it with g as the first argument supplies self manually. This is what calling C.greet(c) does with a real function.
Where binding sits in the lookup order
The following diagram shows the steps for c.greet().
The step "greet in c._dict_?" is where non-data status matters. The next section shows the effect.
Instance attributes shadow methods
Because a function is non-data, the instance dictionary takes priority:
class C:
def greet(self):
return "hi"
c = C()
c.__dict__["greet"] = lambda: "instance"
print(c.greet()) # instance
print(C().greet()) # hiThe lambda takes no arguments. It works because the instance dictionary value is returned as-is, with no __get__ call and no self injected. This is the reason that assigning a function to an instance, c.method = some_function, does not create a method. The function does not receive self. If you want a real bound method on one instance, bind it yourself with types.MethodType(some_function, c). A bound method stored in the instance dictionary is still returned unchanged, but it already carries its self.
The same ordering lets you mock methods in tests by assigning to an instance. It also means a method and an instance attribute with the same name can silently hide each other. A typical bug is setting self.name = name in __init__ when the class also has a def name(self). After that, obj.name() fails with TypeError: 'str' object is not callable.
Callables that do not bind
Binding happens only when the class attribute has a __get__. Objects that are callable but have no __get__ are returned as they are, and they receive no self:
class Adder:
def __call__(self, x):
return x + 1
class K:
add = Adder()
def plain(self, x):
return x + 1
k = K()
print(k.add(1)) # 2
print(k.plain(1)) # 2
print(type(k.add).__name__) # Adder
print(type(k.plain).__name__) # methodHere k.add is the Adder instance itself. Its __call__ is invoked with only x. If you need such an object to behave like a method, give its class a __get__ that returns a bound version, as MyFunction does above.
Built-in functions written in C, such as len, also lack the function __get__, so putting one in a class body does not bind the instance. Methods defined on built-in types use a different descriptor, method_descriptor, which binds in a similar way. You see it with type(str.upper).
What decorators do to binding
A decorator that returns another function keeps binding working, because the result is still a function:
import functools
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
class Service:
@logged
def run(self, n):
return n * 2
print(Service().run(4))This prints calling run and then 8. wrapper is a function stored in the class. Service().run binds it, and args[0] inside the wrapper is the instance.
A decorator that returns an instance of a class without __get__ breaks this. The decorated name becomes a plain callable, and self is never passed. If you write class-based decorators for methods, add __get__.
Performance note
Creating a new method object on every access costs time. CPython avoids this in the common case obj.method(...). The compiler emits a method-call instruction that looks up the function and calls it with obj as the first argument, without building a bound method object. The behavior you can observe is the same as the model above. The shortcut only applies when the attribute is a regular function found on the class and the instance does not override __getattribute__ in a way that prevents it. Storing m = obj.method first does build the bound method, and that object is reusable.
Summary of rules
| Access | Result |
|---|---|
| `C.f` | The function itself, from `__get__(None, C)` |
| `c.f` | A new bound method with `__self__ = c` |
| `c.__dict__["f"]` set | That value, unchanged and not bound |
| Class attribute without `__get__` | Returned as-is, no `self` |
Exercise
Given class A: with def f(self): return 1, and a = A() followed by a.__dict__["f"] = lambda: 2, what do a.f() and A.f(a) return, and why?
Show answer
a.f() returns 2 and A.f(a) returns 1. Functions are non-data descriptors, so the instance __dict__ entry wins on a.f and is returned without binding. A.f is looked up on the class, where function.__get__(None, A) returns the original function, which is then called with a as self.
Exercise
A class-based decorator class Trace: defines __init__(self, func) and __call__(self, *args) that forwards to func. It is applied to a method with @Trace. Calling obj.method() fails because self is missing. What fix restores binding?
Show answer
Add __get__(self, obj, objtype=None) to Trace. Return self when obj is None, otherwise return types.MethodType(self, obj). Then obj.method produces a bound method whose call passes obj as the first argument to Trace.__call__, which forwards it to the wrapped function.