[Python-Dev] __doc__ behavior in class definitions

Phillip J. Eby pje at telecommunity.com
Fri Oct 7 22:28:33 CEST 2005


At 12:15 PM 10/7/2005 -0700, Martin Maly wrote:
>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.

Correct - the scoping rules about local bindings causing a symbol to be 
local only apply to *function* scopes.  Class scopes are able to refer to 
module-level names until the name is shadowed in the class scope.


>Is this bug in Python or are __doc__ strings in classes subject to some
>additional rules?

Neither; the behavior you're seeing doesn't have anything to do with 
docstrings per se, it's just normal Python binding behavior, coupled with 
the fact that the class' docstring isn't set until the class suite is 
completed.

It's currently acceptable (if questionable style) to do things like this in 
today's Python:

     X = 1

     class X:
         X = X + 1

     print X.X  # this will print "2"

More commonly, and less questionably, this would manifest as something like:

     def function_taking_foo(foo, bar):
         ...

     class Foo(blah):
         function_taking_foo = function_taking_foo

This makes it possible to call 'function_taking_foo(aFooInstance, someBar)' 
or 'aFooInstance.function_taking_foo(someBar)'.  I've used this pattern a 
couple times myself, and I believe there may actually be cases in the 
standard library that do something like this, although maybe not binding 
the method under the same name as the function.



More information about the Python-Dev mailing list