Why is the use of an undefined name not a syntax error?
ben.usenet at bsb.me.uk
Sun Apr 1 19:32:46 EDT 2018
David Foster <davidfstr at gmail.com> writes:
> My understanding is that the Python interpreter already has enough
> information when bytecode-compiling a .py file to determine which
> names correspond to local variables in functions. That suggests it has
> enough information to identify all valid names in a .py file and in
> particular to identify which names are not valid.
> If broken name references were detected at compile time, it would
> eliminate a huge class of errors before running the program: missing
> imports, call of misspelled top-level function, reference to
> misspelled local variable.
I'm not sure what you mean by "valid name" and "broken name references".
The usual error is about unbound names, and binding happens at run-time.
Consider this rather contrived example:
x = a
y = 2*a
return x+1 if f2(a) else y+1
('a' is there only to prevent some obvious optimisations.)
Are there any broken name references here? You might get an
UnboundLocalError, though that depends on what f1 and f2 return.
More information about the Python-list