Sub topic 8
Under the hood: how Python binds methods
This chapter assumes you can write classes with instance methods, use @classmethod and @staticmethod, and read decorator syntax. You don't need prior knowledge of descriptors. By the end you will know why t.to_fahrenheit() passes t automatically, why Temperature.from_fahrenheit(212) passes the class, and why is_valid receives nothing extra.
Functions in a class body stay in the class dictionary
When Python runs a class statement, each def creates an ordinary function and stores it in the class's __dict__. A decorator replaces that function with another object. The dictionary shows what is actually stored.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32
@classmethod
def from_fahrenheit(cls, fahrenheit):
return cls((fahrenheit - 32) * 5 / 9)
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
for name in ("to_fahrenheit", "from_fahrenheit", "is_valid"):
print(name, type(Temperature.__dict__[name]).__name__)
# to_fahrenheit function
# from_fahrenheit classmethod
# is_valid staticmethodThe stored objects differ. What you get back from t.to_fahrenheit or Temperature.is_valid is the result of a lookup step that runs when you use the dot.
The descriptor protocol
A descriptor is an object whose class defines a __get__ method. When Python finds a descriptor in a class dictionary during attribute lookup, it calls descriptor.__get__(instance, owner). Here instance is the object you used for the lookup (or None if you used the class), and owner is the class. The return value of __get__ is the value of the attribute expression.
Three kinds of object sit in class dictionaries, and each has a different __get__:
| Stored object | What `__get__` returns | First argument your code receives |
|---|---|---|
| function | a bound method holding the instance (or the plain function if looked up on the class) | the instance, as `self` |
| `classmethod` | a bound method holding the owner class | the class, as `cls` |
| `staticmethod` | the underlying function, unchanged | nothing extra |
Inspecting bound methods
A bound method is a small object that stores two things: the function (__func__) and the value to pass first (__self__). Calling the bound method calls __func__(__self__, *args).
t = Temperature(100)
bound = t.to_fahrenheit
print(bound.__self__ is t) # True
print(bound.__func__ is Temperature.__dict__["to_fahrenheit"]) # True
print(bound()) # 212.0
cm = Temperature.from_fahrenheit
print(cm.__self__ is Temperature) # True
print(Temperature.is_valid is Temperature.__dict__["is_valid"].__func__) # TrueEach line connects to the table above:
t.to_fahrenheitis a bound method whose__self__is the instance. That is whyselfarrives without you passing it.Temperature.from_fahrenheitis a bound method whose__self__is the class. A class method stays bound to a class even when you look it up through an instance.Temperature.is_validis the original function, so no binding happens.
Looking up an instance method on the class gives you the plain function. Temperature.to_fahrenheit(t) works because you supply self yourself.
Writing your own classmethod and staticmethod
The built-ins are small. These versions use the same mechanism and run as shown.
import types
class MyClassMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, owner=None):
if owner is None:
owner = type(obj)
return types.MethodType(self.func, owner)
class MyStaticMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, owner=None):
return self.func
class Shape:
@MyClassMethod
def create(cls):
return cls()
@MyStaticMethod
def describe():
return "a shape"
class Square(Shape):
pass
print(type(Square.create()).__name__) # Square
print(type(Square().create()).__name__) # Square
print(Shape.describe()) # a shapeMyClassMethod.__get__ receives owner=Square when you write Square.create, even though create is defined in Shape. This explains the inheritance behavior from the earlier chapter: cls is decided at lookup time from the class you used, not from the class where the method was written. When you call through an instance, owner is still the instance's class, so Square().create() also builds a Square.
Why instance attributes can shadow methods
A function defines __get__ but not __set__, so it is a non-data descriptor. On lookup, Python checks the instance's __dict__ before using a non-data descriptor from the class. An instance attribute with the same name therefore wins, and it is not bound.
class Box:
def size(self):
return 1
b = Box()
print(b.size()) # 1
b.size = lambda: 99
print(b.size()) # 99, no self was passed
print(Box().size()) # 1, other instances are unaffectedBinding happens only when the function is found on the class. A callable stored on the instance behaves like any other attribute.
Common symptoms and their causes
TypeError: f() takes 0 positional arguments but 1 was given. You defined a method in a class with noself, no decorator, and then called it on an instance. The function was bound, so the instance was passed. Add@staticmethodor add the parameter.- A function assigned to an instance gets no
self. The instance dictionary skips binding, as in theBoxexample. To attach a bound method to one instance, usetypes.MethodType(func, obj). - A callable class attribute is not bound. An object such as
functools.partialhas no__get__, so Python returns it unchanged. Store adeffunction if you need binding.
Exercise
Given class A: @classmethod def make(cls): return cls() and class B(A): pass, what are A.make.__self__ and B().make.__self__? Explain using __get__.
Show answer
A.make.__self__ is A, and B().make.__self__ is B. The classmethod object in A.__dict__ has a __get__(obj, owner) that binds the method to owner. For A.make the owner is A. For B().make the lookup goes through an instance of B, so the owner is type(obj), which is B, even though make is stored in A.
Exercise
Why does Temperature.is_valid is Temperature.__dict__["is_valid"].__func__ print True, while Temperature.from_fahrenheit is Temperature.__dict__["from_fahrenheit"].__func__ prints False?
Show answer
The staticmethod.__get__ returns the underlying function unchanged, so the lookup gives back the same object stored in __func__. The classmethod.__get__ creates a new bound method object that wraps the function and the class. That bound method is a different object from the raw function.