Namespaces in functions vs classes

Terry Reedy tjreedy at udel.edu
Tue Apr 19 13:18:35 EDT 2011


On 4/19/2011 10:58 AM, Gerald Britton wrote:

> serve method unless it is qualified.  I now understand the Python does
> not consider a class definition as a separate namespace as it does for
> function definitions.

Class namespaces are separate namespaces but not in the same way as for 
functions. Class bodies are executed, once, in the new class namespace 
when the class statement is executed. That new namespace is then 
attached to the new class object. Function bodies are not executed when 
the function statement is executed, but are merely compiled for repeated 
execution later, when the function is called.

It might help to know:

1. In early Python, nested functions could *not* access the namespace of 
enclosing functions.

2. Functions do not *belong* to a particular class. The following two 
snippets are equivalent:

a = 'out'
class C:
     a = 'in'
     def f():
         print(C.a)
C.f()
# prints 'in'

a = 'out'
class C:
     a = 'in'
def f():
     print(C.a)
C.f = f
C.f()
#prints 'in'


3. Default argument expressions *are* executed in the namespace where 
the def statement appears. The following two snippets are *not* equivalent

a = 'out'
class C:
     a = 'in'
     def f(x=a): print(x)
C.f()
# prints 'in'

a = 'out'
class C:
     a = 'in'
def f(x=a): print(x)
C.f = f
C.f()
# prints 'out'


-- 
Terry Jan Reedy




More information about the Python-list mailing list