[Python-ideas] Why does += trigger UnboundLocalError?
Carl M. Johnson
cmjohnson.mailinglist at gmail.com
Wed Jun 1 10:26:02 CEST 2011
More information about the Python-ideas mailing list
Wed Jun 1 10:26:02 CEST 2011
- Previous message: [Python-ideas] Why does += trigger UnboundLocalError?
- Next message: [Python-ideas] Why does += trigger UnboundLocalError?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Tue, May 31, 2011 at 9:05 PM, Georg Brandl <g.brandl at gmx.net> wrote: > Sure, this can only work if the local is assigned somewhere before the > augmented > assign statement. But this is just like accessing a local before its > assignment: in the case of > > x = 1 > def f(): > print x > x = 2 > > we also don't treat the first "x" reference as a nonlocal. > I don't think that's a counterexample to the point I'm trying to make. We all agree that if there's an x= somewhere in the function body, then we have to treat the variable as a local. The only possible way around that would be to solve the halting problem in order to figure out if a particular line of code will be reached or not. Agreed, sure, we have to treat the LHS of = as a local. But += is fundamentally different. You cannot have a += statement unless somewhere out there there is a matching = statement. It cannot exist independently. It never works on its own. So, if there is a += statement in the function body and there isn't an = statement in the function body it cannot work. Ever. All function bodies that have a += but no corresponding = or nonlocal are, as of today, broken code. So, if we were to change Python to make += not cause a variable to become a local, it wouldn't change how any (working) Python code today functions (it might causes some tests to change if they were counting on the error). This would be a completely backwards compatible change. Or am I missing something? Is there any scenario where you can get away with using += without = or nonlocal? I guess you could do something with locals().update or the stackframe, but my understanding is that those hacks don't count for language purposes. -- Carl -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110531/3e26b148/attachment.html>
- Previous message: [Python-ideas] Why does += trigger UnboundLocalError?
- Next message: [Python-ideas] Why does += trigger UnboundLocalError?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-ideas mailing list