[Python-Dev] __doc__ behavior in class definitions

Steve Holden steve at holdenweb.com
Fri Oct 7 22:33:57 CEST 2005


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__
> 
> print c.__doc__
> # module end
> 
> When ran, it prints:
> 
> module doc
> class doc
> class doc
> 
> 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?
> 
Well, it's nothing to do with __doc__, as the following example shows:

crud = "module crud"

class c:
     print crud
     crud = "class crud"
     print crud

print c.crud

As you might by now expect, this outputs

module crud
class crud
class crud

Clearly the rules for class scopes aren't quite the same as those for 
function scopes, as the module

crud = "module crud"

def f():
     print crud
     crud = "function crud"
     print crud

f()

does indeed raise an UnboundLocalError exception.

I'm not enough of a language lawyer to determine exactly why this is, 
but it's clear that class variables aren't scoped in the same way as 
function locals.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/



More information about the Python-Dev mailing list