[Python-Dev] __doc__ behavior in class definitions

Jack Diederich jack at performancedrivers.com
Fri Oct 7 22:52:37 CEST 2005


On Fri, Oct 07, 2005 at 12:15:04PM -0700, Martin Maly wrote:
> Hello Python-Dev,
>  
> My name is Martin Maly and I am a developer at Microsoft, working on the
> IronPython project with Jim Hugunin. I am spending lot of time making
> IronPython compatible with Python to the extent possible.
> 
> I came across a case which I am not sure if by design or a bug in Python
> (Python 2.4.1 (#65, Mar 30 2005, 09:13:57)). Consider following Python
> module:
> 
> # module begin
> "module doc"
> 
> class c:
>     print __doc__
>     __doc__ = "class doc"			(1)
>     print __doc__
>
[snip]
>
> Based on the binding rules described in the Python documentation, I
> would expect the code to throw because binding created on the line (1)
> is local to the class block and all the other __doc__ uses should
> reference that binding. Apparently, it is not the case.
> 
> Is this bug in Python or are __doc__ strings in classes subject to some
> additional rules?

Classes behave just like you would expect them to, for proper variations
of what to expect *wink*.

The class body is evaluated first with the same local/global name lookups
as would happen inside another scope (e.g. a function).  The results
of that evaluation are then passed to the class constructor as a dict.
The __new__ method of metaclasses and the less used 'new' module highlight
the final step that turns a bucket of stuff in a namespace into a class.

>>> import new
>>> A = new.classobj('w00t', (object,), {'__doc__':"no help at all", 'myself':lambda x:x})
>>> a = A()
>>> a.myself()
<__main__.w00t object at 0xb7bc32cc>
>>> a
<__main__.w00t object at 0xb7bc32cc>
>>> help(a)
Help on w00t in module __main__ object:

class w00t(__builtin__.object)
 |  no help at all
 |  
 |  Methods defined here:
 |  
 |  lambdax
 |
>>>

Hope that helps,

-jackdied


More information about the Python-Dev mailing list