unintuitive for-loop behavior
Brendan Abel
007brendan at gmail.com
Fri Sep 30 13:03:03 EDT 2016
> 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
a = 1
if condition:
b = a + 2
print b # UnboundLocalError: local 'b' referenced before assignment
for x in sequence:
print x
print x # UnboundLocalError: local 'x' referenced before assignment.
----------
I wouldn't call either behavior intuitive or unintuitive. They're just
different behaviors of different languages.
On Fri, Sep 30, 2016 at 5:33 AM, Steve D'Aprano <steve+python at pearwood.info>
wrote:
> On Fri, 30 Sep 2016 05:29 am, namenobodywants at gmail.com wrote:
>
> > hello pythonistas
> >
> > i've had a nodding acquaintance with python for some time, and all along
> i
> > assumed that for-loops got a namespace of their own;
>
> Giving for-loops their own namespace is a grossly unintuitive and a very
> weird thing to do. Modules, classes and functions are obviously namespaces.
> Why should arbitrary syntactic structures create their own namespace?
>
> It would be terribly inconvenient and surprising for if...else blocks to be
> separate namespaces:
>
> 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
>
>
> unless you declared it nonlocal or global, depending on whether your for
> loop was inside a function or not.
>
> To me, "make for-loops be their own scope" sounds like a joke feature out
> of
> joke languages like INTERCAL. I'm not aware of any sensible language that
> does anything like this.
>
> No, wait a minute, I tell a lie, I recall Chris Angelico mentioning that
> one
> of his favourite languages, Pike or REXX, does it. I forget which.
>
>
>
>
> --
> Steve
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list