Look at this familiar code:
class Foo(object):
def __init__(self, a):
self.a = a
def bar(self, b):
return self.a + b
foo = Foo(1)
How do __init__ and bar get that self parameter?
Unbound methods
Well, bar is just a plain old function. (I'll just talk about bar for simplicity, but everything is also true for __init__, except for one minor detail I'll get to at the end.)
Foo.bar is a method, but it's an "unbound method"—that is, it's not bound to any particular Foo instance yet. As it turns out, these are exactly the same objects as plain old functions. (This wasn't true in Python 2.x, but I'll get to that later.)
You can call unbound methods just like any other function—but to do so, you have to pass an extra argument explicitly as self:
>>> Foo.bar
<function __main__.bar>
>>> Foo.bar(foo, 2)
3
You can even save them as plain old variables outside a class.
>>> bar = Foo.bar
>>> bar(foo, 2)
3
This also means you monkeypatch a class to add new methods very easily:
>>> def baz(self):
... return self.a * 2
>>> Foo.baz = baz
>>> Foo.baz(foo)
2
>>> foo.baz()
2
This even affects existing instances of the class (as long as they haven't shadowed the method with an instance variable by assigning to self.baz somewhere).
Bound methods
While Foo.bar is the same thing as bar, foo.bar is _not_ the same thing. It's a method, not a function:
>>> foo.bar
<bound method Foo.bar of <__main__.Foo object at 0x1066463d0>>
As you may be able to guess from the repr, a bound method wraps up a function and an object. And you can even pull them out:
>>> foo.bar.__func__ is Foo.bar
True
>>> foo.bar.__self__ is foo
True
This means that monkeypatching an instance is a bit more complicated, because you have to build a method. How do you do that?
Well, you could create a whole new class with the method, create an instance of that class, and copy the method from the new instance to the one you want to patch. But that's pretty ugly.
Think about how you construct other types. To make a Foo, you just call Foo(1). To make an int, you just call int('1'). The same goes for list, str, bytearray, and so on.
But what's the type of a method? Well, it's "method", but there's no built-in name bound to that.
For types that aren't normally useful, but occasionally are, Python hides the names, but gives us the
types module to access them. So:
>>> help(types.MethodType)
Help on class method in module builtins:
class method(object)
| method(function, instance)
…
>>> foo.baz = types.MethodType(baz, foo)
>>> foo.baz()
2
How do bound methods work?
Any type can be callable, not just functions. You can define your own callable types just by defining a __call__ method. So, you can simulate a bound method pretty easily:
class BoundMethod(object):
def __init__(self, function, instance):
self.__func__, self.__self__ = function, instance
def __call__(self, *args, **kwargs):
return self.__func__(self.__self__, *args, **kwargs)
Now you can use this exactly like the above:
>>> foo.baz = BoundMethod(baz, foo)
>>> foo.baz()
2
How do bound methods get built?
Everything above, you could simulate yourself, without knowing anything deep about Python.
But there's one piece you can't. How is it that Foo.bar is an unbound method, but foo.bar is a bound method?
The obvious (and wrong) answer would be: When constructing a class instance, Python could create a bound method out of each unbound method and copy them in. That would be easy. But that wouldn't explain why adding Foo.bar made foo.bar work, even though foo had already been created.
In fact, you can look at the __dict__ for the objects and see that Python hasn't done this; the only thing that exists is the unbound method on Foo:
>>> Foo.__dict__
{'bar': <function Foo.bar at 0x1086259e0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, …}
>>> foo.__dict__
{'a': 1, 'baz': <__main__.BoundMethod at 0x106646c10>}
The foo.baz that we created and added explicitly is there, but foo.bar isn't there. It's inherited from Foo.bar, just like any class attribute.
Except that normally, a class attribute doesn't magically change value or type when accessed from an instance:
>>> class Spam(object):
... eggs = 2
>>> spam = Spam()
>>> spam.eggs
2
So, why is this different if the attribute is a function?
Descriptors
The secret is
descriptors.
Descriptors have a reputation for being scary, deep magic. But once you understand what good they are, it's not too hard to understand why they work.
Every value in Python can have __get__, __set__, and __delete__ methods.
When you access a class attribute through an instance, if that the attribute has a __get__ method, it gets called with the instance and class, and whatever __get__ returns is what you see.
So, a function's __get__ method works like this:
def __get__(self, instance, owner):
return types.MethodType(self, instance)
And that's nearly all there is to it. I've cheated a little bit (e.g., the same __get__ has to work to return a bound method when accessed on an instance, a plain function when accessed directly on a class), but it's all pretty simple.
Putting it all together:
When you ask for foo.bar, Python looks in foo.__dict__, and doesn't find anything. So then it goes to foo's class and looks in Foo.__dict__, and finds something named "bar". Because "bar" was accessed through the class dictionary, Python calls Foo.bar.__get__(foo, Foo), which returns a bound method.
A classmethod is just a function whose __get__ returns types.MethodType(self, cls), which means you end up with a bound method bound to the class, rather than an instance. And a staticmethod is just a function whose __get__ returns itself. A property is just an attribute whose __get__, __set__, and __delete__ methods call the functions you defined in your @property. And so on. When you look behind the curtain, the wizard isn't that scary at all.
You can read more about descriptors in the
Descriptor HowTo Guide.
History
You may have noticed that we have actual types for functions and bound methods, but unbound methods are just the same thing as functions. Why even have a name for something if it's just a confusing synonym of something everyone understands?
You may have also noticed that __get__ takes an owner parameter that nobody uses.
In Python 2.x, unbound methods were a different type from functions, and very closely related to bound methods.
A Python 3 bound method has attributes __func__ and __self__. In Python 2, these were called im_func and im_self, and there was a third called im_class. A method with None for im_self was an unbound method; otherwise, it was a bound method. You should be able to imagine how functions and @classmethods and @staticmethods implemented __get__.
As it turns out, unbound methods don't add much. They make calls a little slower, make it as hard to monkeypatch classes (which is relatively common) as instances (which is uncommon), and add a whole new concept that you need to understand the complexities of. What do you get in exchange? Basically, just the fact that they can tell you which class they're part of. But really, the only thing you want to do with that is display it—which __qualname__ does a much better job at—or try to use it for pickling—which doesn't work anyway.
Python 2.x also has some wrinkles dealing with classic classes, but these only come up in three cases:
- Ancient code written to be compatible with Python 1.5-2.1.
- Simple bugs by novices who don't know how to write a new-style class.
- Troll code by people who insist that they prefer classic classes just because the core devs and everyone else in the Python community disagrees.
What was that about __init__?
I was hoping you'd forget…
Python
reserves the right to treat special methods specially.
What's a special method? This isn't actually quite defined anywhere. But basically, it's any method whose name begins and ends with double underscores, and whose purpose is to be called by the language itself or by some builtin code. (Note that most implementations provide a way for extension modules to add new builtin code—that's what the C API, the Jython bridge, etc. are all about.)
How are they treated specially? Basically, for some special methods, in some cases, Python ignores __getattr__, __getattribute__ and any other attribute mechanism besides __dict__, and skips the instance __dict__ to go straight to the class and its base classes.
For different implementations, and even different versions of the same implementation, the set of methods and cases and the exact details of the specialness differ. If you want to know about CPython does, look at the source to
_PyObject_LookupSpecial, and grep for calls to it in the Python, Objects, and Modules directories.
Anyway, in CPython 3.3, when calling __init__ as part of object construction when you haven't overridden __new__, you go through
_PyObject_LookupSpecial; in other cases, it's a normal lookup.
Of course it kind of makes sense for __init__. Normally, an instance's dict is empty until the __init__ method, and methods like __getattr__ often need setup that's done in __init__ to work.
View comments