Eli Bendersky, 09.05.2011 14:56:
It's a known Python gotcha (*) that the following code:

x = 5
def foo():
     print(x)
     x = 1
     print(x)
foo()

Will throw:

        UnboundLocalError: local variable 'x' referenced before assignment

On the usage of 'x' in the *first* print. Recently, while reading the
zillionth question on StackOverflow on some variation of this case, I
started thinking whether this behavior is desired or just an implementation
artifact.

Well, basically any compiler these days can detect that a variable is being used before assignment, or at least that this is possibly the case, depending on prior branching.

ISTM that your suggestion is to let x refer to the outer x up to the assignment and to the inner x from that point on. IMHO, that's much worse than the current behaviour and potentially impractical due to conditional assignments.

However, it's also a semantic change to reject code with unbound locals at compile time, as the specific code in question may actually be unreachable at runtime. This makes me think that it would be best to discuss this on the python-ideas list first.

If nothing else, I'd like to see a discussion on this behaviour being an implementation detail of CPython or a feature of the Python language.

Stefan

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to