[Python-Dev] more timely detection of unbound locals
ijmorlan at uwaterloo.ca
Mon May 9 17:44:21 CEST 2011
On Mon, 9 May 2011, Eli Bendersky wrote:
>> x = 5
>> def foo ():
>> print (x)
>> if bar ():
>> x = 1
>> print (x)
> I wish you'd annotate this code sample, what do you intend it to
> It probably shows the original complaint even more strongly. As for being a
> problem with the suggested solution, I suppose you're right, although it
> doesn't make it much different. Still, before a *possible* assignment to
> 'x', it should be loaded as LOAD_NAME since it was surely not bound as
> local, yet.
Extrapolating from your suggestion, you're saying before a *possible*
assignment it will be treated as global, and after a *possible* assignment
it will be treated as local?
x = 1
should always print the same thing twice (in the absence of actions taken
by other threads)!
Replace "False" by something that is usually (but not always) True, and
"print (x)" by something that actually does something, and you had best
put on your helmet because it's going to be a fun ride.
But I won't be on it.
The idea that the same name within the same scope always refers to the
same value is an idea from functional programming and not part of Python;
but surely the same name within the same scope should at least always
refer to the same variable!
If something is to be done here, it occurs to me that the same parser that
decides that the initial reference to x should use the local x could
conceivably issue an error right away - "local variable can never be
assigned before use" rather than waiting until runtime. But even if I
haven't confused myself about the possibility of this raising a false
positive (and it certainly could in the presence of dead code), it
wouldn't catch cases of conditional premature use of a local variable. I
think in those cases people would still ask the same questions they do
with the existing implementation.
Isaac Morland CSCF Web Guru
DC 2554C, x36650 WWW Software Specialist
More information about the Python-Dev