3 ms·
> I know there's no such thing as variable declaration and variable initialization in Python. That is not quite true, the first assignment is an implicit decla
by masklinn 10y ago
> I know there's no such thing as variable declaration and variable initialization in Python.
That is not quite true, the first assignment is an implicit declaration, and will set up a slot in the enclosing code object, which is why you get an UnboundLocalError if you use a name before it's first assigned to:
>>> def foo():
... a
... a = 3
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'a' referenced before assignment
but a NameError if you use a name which is not assigned to at all:
>>> def foo():
... a
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
NameError: name 'a' is not defined
In the latter case the slot doesn't exist at all in the lexical context, while in the former there is a slot set up but it has no value associated to it.
- happy-go-lucky 10y agoI agree, but these are problems with Python's implicit variable declaration.
- masklinn 10y agoThat's orthogonal to my demonstration that there is in fact "such a thing as variable declaration and initialisation in Python", given that the cases of an undeclared variable and a declared but unassigned to variable both exist with very different errors.