unintuitive for-loop behavior
Chris Angelico
rosuav at gmail.com
Fri Sep 30 13:08:25 EDT 2016
On Sat, Oct 1, 2016 at 3:03 AM, Brendan Abel <007brendan at gmail.com> wrote:
>> a = 1
> if condition:
> print(a) # UnboundLocalError: local 'a' referenced before assignment
> a += 1
>
>
> For-loops are no different. Making them their own namespace is a very
> strange thing to do, it would mean you couldn't re-bind a value inside a
> for-loop:
>
> count = 0
> for x in sequence:
> count += 1
> # raises UnboundLocalError: local 'count' referenced before assignment
>
> --------------
>
> That's generally not how nested scopes work, you could still reference
> objects in the outer scope from the inner scope, but the outer scope
> couldn't reference objects in the inner scope
The trouble is that, absent some sort of declaration, there's no way
for the compiler to know whether 'count' and 'a' are supposed to be
new variables in the inner scope, or the same variable as the one in
the next scope out. In Python, declarations are used when you rebind
nonlocal or global names, so these examples would have to be written
thus:
a = 1
if condition:
nonlocal a
print(a)
a += 1
count = 0
for x in sequence:
nonlocal count
count += 1
I don't think we want that. :)
ChrisA
More information about the Python-list
mailing list