magic names in python

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon Jun 4 19:03:39 EDT 2007


On Mon, 04 Jun 2007 22:19:35 +0000, Lenard Lindstrom wrote:

> What is "magic" about __init__ and __repr__? They are identifiers just 
> like "foo" or "JustAnotherClass". They have no special meaning to the 
> Python compiler. The leading and trailing double underscores represent 
> no special incantation. It is just a naming convention.

That's not quite true, as you point out:

> So a number of method names like __init__ and __repr__ have a 
> pre-defined usage. 

That makes them magic, in the best possible way.


> In every other respect they are just normal methods. 

That is *almost* true. Or, to put it another way, that is wrong. Some of
the double-underscore magic methods are automatically called on the class
instead of the instance, bypassing normal inheritance. 


>>> import new
>>> class Test(object):
...     def foo(self):
...             return "foo called from the class"
...     def __str__(self):
...             return "__str__ called from the class"
...
>>> obj = Test()
>>> obj.foo()
'foo called from the class'
>>> str(obj) # calls obj.__str__
'__str__ called from the class'

Now see what happens when we add methods to the instance.

>>> obj.foo = new.instancemethod(
... lambda self: "foo called from the instance", obj, Test)
>>> obj.foo()
'foo called from the instance'
>>> obj.__class__.foo(obj) # Check the method in the class is still there.
'foo called from the class'

So calling a random method like foo() goes through the usual procedure:
check the instance, then check the class. Now let's try it with a magic
method.


>>> obj.__str__ = new.instancemethod(
... lambda self: "__str__ called from the instance", obj, Test)
>>> obj.__str__()
'__str__ called from the instance'
>>> str(obj) # calls obj.__str__() maybe?
'__str__ called from the class'



[snip]
> Back to "magic names". Python is a consistent language. What may be 
> special cased - "magic" - in another language is handled normally with 
> Python's general purpose dynamic type system. In fact I can think of 
> only one name I would call "magic": __future__.

Certainly I think __future__ is *more* magic than other double-underscore
names.



-- 
Steven.




More information about the Python-list mailing list