Sub topic 8
Under the hood: how Python binds methods
This chapter explains the mechanism behind self, cls, and the "no first argument" behavior of static methods. You will see that all three come from one rule, the descriptor protocol. Once you know it, you can predict what any attribute access on a class or instance returns.
It assumes you can define classes with instance, class, and static methods, and that you know what an instance __dict__ is. You do not need to have written a descriptor before.
Methods are looked up, then bound
When you write obj.method(), Python does two separate things:
- It evaluates the expression
obj.method, which looks up the name and produces an object. - It calls that object with the arguments in parentheses.
Binding happens in step 1. The lookup does not just return what is stored in the class. It may transform the stored object on the way out. Start by looking at what an ordinary function turns into:
class Greeter:
def hello(self):
return "hi"
g = Greeter()
bound = g.hello
print(type(bound).__name__) # method
print(bound.__self__ is g) # True
print(bound.__func__ is Greeter.__dict__["hello"]) # True
print(type(Greeter.hello).__name__) # function
print(Greeter.hello(g)) # hi
print(bound == g.hello, bound is g.hello) # True FalseThree facts follow from this output:
- The class stores a plain function in its
__dict__. g.hellois a different kind of object, a bound method. It holds the instance in__self__and the original function in__func__.- Each access to
g.hellobuilds a new bound method object. The two compare equal but are not the same object.
Accessing the function through the class, as in Greeter.hello, gives back the plain function. In Python 3 there are no "unbound methods". That is why Greeter.hello(g) works: you pass self by hand.
The descriptor protocol
A descriptor is an object stored as a class attribute whose type defines at least one of these methods:
| Method | Signature | Purpose |
|---|---|---|
| `__get__` | `__get__(self, obj, objtype=None)` | Customize reading the attribute |
| `__set__` | `__set__(self, obj, value)` | Customize assigning the attribute |
| `__delete__` | `__delete__(self, obj)` | Customize deleting the attribute |
Functions define __get__. That one method is the whole reason methods work. When attribute lookup finds a function in a class, it calls function.__get__(obj, objtype). The result depends on the arguments:
- If
objis an instance, the function returns a bound method that remembersobj. - If
objisNone, which happens for access through the class, the function returns itself.
You can call __get__ yourself and get the same result as normal access:
class Greeter:
def hello(self):
return "hi"
g = Greeter()
func = Greeter.__dict__["hello"]
manual = func.__get__(g, Greeter)
print(manual()) # hi
print(func.__get__(None, Greeter) is func) # Trueclassmethod and staticmethod are two more descriptor types. Each defines __get__ and decides what to hand back:
| Stored in the class as | `Class.name` returns | `instance.name` returns |
|---|---|---|
| function | the plain function | a method bound to the instance |
| `classmethod` object | a method bound to `Class` | a method bound to `type(instance)` |
| `staticmethod` object | the plain function | the plain function |
The decorator syntax is only a rebinding of the name. These two definitions are identical:
class A:
@classmethod
def make(cls):
return cls()
class B:
def make(cls):
return cls()
make = classmethod(make)Rebuilding classmethod and staticmethod
The built-in versions are written in C, but their behavior fits in a few lines of Python. Rebuilding them shows that nothing special is going on:
import types
class MyClassMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if objtype is None:
objtype = type(obj)
return types.MethodType(self.func, objtype)
class MyStaticMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
return self.func
class Demo:
@MyClassMethod
def who(cls):
return cls.__name__
@MyStaticMethod
def add(a, b):
return a + b
class SubDemo(Demo):
pass
print(Demo.who()) # Demo
print(SubDemo.who()) # SubDemo
print(Demo().who()) # Demo
print(SubDemo().who()) # SubDemo
print(Demo().add(2, 3)) # 5types.MethodType(func, x) is the constructor for bound methods. It creates an object that calls func(x, *args) when called. The class method version binds the class instead of the instance. That is the entire difference.
The key line is objtype. Python passes the class used for the lookup, not the class that defines the method. For SubDemo.who, objtype is SubDemo even though who lives in Demo.__dict__. This is why cls reflects subclasses, as an earlier chapter showed.
The static method's __get__ ignores both arguments and returns the stored function. Nothing is bound, so nothing is inserted into the call.
Watching __get__ run
A tracing wrapper makes the calls visible. It wraps a function, prints what it receives, and then delegates to the function's own __get__:
class Trace:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
print(f"__get__ obj={obj!r} objtype={objtype.__name__}")
return self.func.__get__(obj, objtype)
class A:
@Trace
def f(self):
return "called"
def __repr__(self):
return "<A>"
a = A()
print(a.f())
print(A.f(a))The output is:
__get__ obj=<A> objtype=A
called
__get__ obj=None objtype=A
calledAccess through the instance passes the instance. Access through the class passes None. Both calls receive the class. The __get__ call happens at the moment of the dot, before the parentheses are evaluated.
The attribute lookup order
The algorithm that decides when __get__ runs is part of object.__getattribute__. The behavior depends on whether a descriptor is a data descriptor or a non-data descriptor:
- A data descriptor defines
__set__or__delete__(usually both with__get__). Apropertyis one. - A non-data descriptor defines only
__get__. Functions,classmethod, andstaticmethodare all non-data descriptors.
For obj.name, Python checks these sources in order:
Because functions are non-data descriptors, a value in the instance __dict__ hides a method of the same name. This leads to a gotcha covered below.
For access through a class, as in Class.name, the lookup is done by type.__getattribute__. It searches the class and its parents, then calls __get__(None, Class) on whatever it finds. This is why Class.method gives a plain function and Class.some_classmethod gives a bound method.
Inspecting what is really stored
Normal access runs __get__, so getattr shows you the transformed result. To see what the class actually holds, use inspect.getattr_static or read the class __dict__:
import inspect
class T:
@classmethod
def c(cls):
return cls
@staticmethod
def s():
return "s"
def i(self):
return self
for name in ("c", "s", "i"):
raw = inspect.getattr_static(T, name)
print(name, type(raw).__name__, type(getattr(T, name)).__name__)
print(T.c.__self__ is T) # True
print(T().i.__self__ is not None) # TrueThe output is:
c classmethod method
s staticmethod function
i function functionThe first column is the name. The second is the stored type. The third is what normal access gives you.
Reading T.__dict__["c"] gives the raw classmethod object, and the raw object is not directly usable. Calling T.__dict__["c"]() raises TypeError: 'classmethod' object is not callable. A raw staticmethod object became callable in Python 3.10, but a raw classmethod still is not. Go through getattr or normal dot access when you want a callable.
Consequences you can observe
Assigning a function to an instance does not bind it
Binding is done by the class-level descriptor. A function stored in an instance __dict__ is returned as is:
import types
class C:
def m(self):
return "class"
c = C()
c.m = lambda: "instance"
print(c.m()) # instance, called with no self
print(C().m()) # class
c.m = types.MethodType(lambda self: "bound by hand", c)
print(c.m()) # bound by handThe first assignment shadows the method for that one instance only, and no self is passed. If you want a per-instance method that receives self, build it with types.MethodType. Most of the time, a better design is to avoid this pattern.
Assigning a function to a class binds it
Because the descriptor lives in the class, a function added to the class after creation behaves like any other method, including for instances that already exist:
class K:
pass
k = K()
def late(self):
return "bound now"
K.late = late
print(k.late()) # bound nowCallables that are not descriptors are not bound
Only objects with a __get__ method bind. functools.partial objects and built-in functions such as len do not have one, so they are returned unchanged and no self is inserted:
from functools import partial
def add(a, b):
return a + b
class Calc:
plus_one = partial(add, 1)
def plus_two(self, x):
return add(2, x)
print(Calc().plus_one(5)) # 6
print(Calc().plus_two(5)) # 7plus_one(5) calls add(1, 5). If it had been a plain function with two parameters, self would have taken the first slot. If you want a partial that binds like a method, use functools.partialmethod.
Every access creates a bound method
Bound method objects are created on each dot access. In a hot loop, the cost can be visible. Look the method up once and reuse the result:
items = []
append = items.append # bind once
for n in range(5):
append(n)
print(items) # [0, 1, 2, 3, 4]For a normal program, this is a micro-optimization. Do not do it unless a profiler points at it.
What this means for your design choices
The descriptor model explains several rules of thumb from earlier chapters:
- A class method gets
clsfrom the lookup, not from the definition. That is why it supports inheritance, and why hard-codingShape()inside a class method defeats subclasses. - A static method is just a function that opts out of binding. It is the right choice when no instance or class is needed, and the call site can use either the class or an instance.
- An instance method called through the class needs an explicit instance:
Class.method(obj). This is occasionally useful for calling a parent implementation, as inBase.method(self). Prefersuper()in new code.
The model also explains a few cautions:
- Stacking
@classmethodon top of@propertyonce worked, by lettingclassmethodforward__get__to the property. It was deprecated in Python 3.11 and removed in 3.13. Do not rely on it. - Decorators that return something other than a function, such as a callable class instance without
__get__, break binding. A method wrapped this way receives noself. Wrap withfunctools.wrapsinside a function decorator, which returns a real function, or give your wrapper class a__get__method. - Functions placed directly in a class body also become methods. A helper defined in the class body and called at class creation time is a plain function at that moment, but it becomes a method for instances later.
Summary
- Attribute lookup, not the call, is where binding happens.
- Functions,
classmethod, andstaticmethodare non-data descriptors with a__get__(obj, objtype)method. - A function returns itself for class access and a bound method for instance access. A class method binds the class either way. A static method never binds.
- The instance
__dict__outranks non-data descriptors, so an instance attribute can hide a method. inspect.getattr_staticshows what is stored without running__get__.
Exercise
In the class below, obj.greet is assigned a plain function that takes one parameter. Why does obj.greet() raise a TypeError, and how do you make name receive the instance? class P: pass, obj = P(), def greet(name): return "hi " + str(name), obj.greet = greet.
Show answer
The function is stored in the instance __dict__, and binding only happens when a descriptor is found on the class. Python returns the function unchanged, so obj.greet() supplies no argument and name is missing. Bind it by hand with types.MethodType(greet, obj), or assign the function to the class (P.greet = greet) so the class-level lookup calls greet.__get__(obj, P).
Exercise
Write a descriptor class ClassOnly that wraps a function and binds it to the class, like classmethod, but raises AttributeError when accessed through an instance. What does __get__ receive as obj for class access?
Show answer
For class access, obj is None. A solution: class ClassOnly: with __init__(self, func) storing self.func = func, and __get__(self, obj, objtype=None) that does if obj is not None: raise AttributeError("class access only"), then return types.MethodType(self.func, objtype). Calling Demo.method() works, and Demo().method raises.
Exercise
Given class T: with a @staticmethod named s, what do type(T.__dict__["s"]).__name__ and type(T.s).__name__ print, and why do they differ?
Show answer
The first prints staticmethod and the second prints function. The class dictionary holds the raw staticmethod descriptor. Normal access T.s calls its __get__, which returns the wrapped function without binding anything.