I know python treats this namespace in a different way ever since I found out about
def foo(l=[]):
l.append(1)
print(l)
foo()
foo()
foo([])
foo()
which prints the following.
[1]
[1,1]
[1]
[1,1,1]
So I was sceptical about their use as an object initializers. Then recently I encountered another similarly strange behaviour, demonstrated below.
class Foo:
bar = 0
def __init__(self):
self.a = bar
Foo()
This raises an exception as bar is not defined inside this namespace.
class Foo:
bar = 0
def __init__(self, a=bar)
self.a = a
Foo()
Now this successfully assigns value held by a class variable foo to an object a inside the initializer.
Why do these things happen and how are the default argument values treated?
barin the class scope is sort of orthogonal to the issue of default values. What you need to understand is that class bodies do not form an enclosing scope, which is why you must always useself.barwithin the function bodies of methods defined in the class body. Also note, values do not have namespaces per se, rather, various namespaces can reference the same value. However, default values are evaluated once at function definition time, and they have access to the scope of where the function is defined for whatever expression you are using__defaults__if you want to know where a function's default arguments are actually stored.