[Python-ideas] Why does += trigger UnboundLocalError?

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Wed Jun 1 11:41:06 CEST 2011


On Tue, May 31, 2011 at 11:09 PM, Jacob Holm <jh at improva.dk> wrote:
>
> x = 1
> > def f():
> > # The next statement uses the global x
> > x += 1
> > x = 2
> > # From here, you have a local x
> >
>>> Specifically, the "x = 2" statement (and the lack of a nonlocal
> statement) forces x to be local throughout the function, and the "x +=
> 1" statement then tries to read the local "x" and fails.
>
Yes, Jacob has got exactly what I was proposing. x += 1; x = 2 should
continue to fail, since there would be a = statement in the function body in
that case.
-- Carl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110531/339a5b43/attachment.html>


More information about the Python-ideas mailing list

AltStyle によって変換されたページ (->オリジナル) /