Python 3 removes name binding from outer scope

Chris Angelico rosuav at gmail.com
Tue Jul 25 04:43:15 EDT 2017


On Tue, Jul 25, 2017 at 6:10 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> I think those are not the only two options (the “except clause has its
> own scope” behaviour is an option that could have been chosen, for
> example).
>
> At this point the behaviour and motivation are clear, having been
> revealed; I disagree with the behaviour, and think the motivation could
> have been met better.

Having a new scope introduced by a non-function would also be
surprising. List comprehensions (as of Py3) introduce a new scope, but
they do so by being wrapped in a function. Would you expect that an
except block is wrapped in a function too? And whether or not it's a
function, the fact would remain that except blocks would differ from
other name-binding blocks (with/as and for). There's a reasonable
argument for with/as to introduce a new scope, but a for loop
definitely shouldn't, so there's going to be a difference there.

And if it's its own function, you'd need to use nonlocal/global inside
it to make any other changes. That would be a royal pain. Consider:

try:
    raw_input
except NameError:
    global raw_input # blech
    raw_input = input

I'm not actually sure what happens if you use a global declaration at
top level. Is it ignored? Is it an error?

One potential solution would be to have *just the exception name* in a
sort of magic scope. But I'm not sure how that would go.

TBH, I rather suspect that the exact semantics here aren't too
critical. If there's a solid argument for some variation on the
current system, one that still prevents the refloop between the
exception and a function's variables, it'd be worth discussing as a
proposal. At very least, it's worth raising it on -ideas... worst
case, it gets shut down quickly.

ChrisA



More information about the Python-list mailing list