Quirk difference between classes and functions
On Tue, Feb 26, 2019 at 5:06 PM Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Chris Angelico wrote:
> > Classes and functions behave differently. Inside a function, a name is
> > local if it's ever assigned to; but in a class, this is not the case.
> Actually, it is. Assigning to a name in a class body makes it part
> of the class namespace, which is the local namespace at the time
> the class body is executed.
The significant part here is "ever". Consider:
>>> x = 1
>>> def f():
... x = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'x' referenced before assignment
>>> class X:
... x = 2
In the function, since x *is* assigned to at some point, it is deemed
a local name, which means that referencing it bombs. In the class,
that isn't the case; until it is actually assigned to, it isn't part
of the class's namespace, so the global is visible.
So, yes, it's a difference between function namespaces and other
namespaces (modules work the same way as classes).