interesting. it’s still assignment, even if nothing gets assigned (and only __iadd__ gets called behind the scenes).



2014-04-26 15:54 GMT+02:00 Chris Angelico <rosuav@gmail.com>:
On Sat, Apr 26, 2014 at 11:43 PM, Philipp A. <flying-sheep@web.de> wrote:
> sure it works if `eggs` has a `__iadd__` method. why shouldn’t it use the
> outer local?

1) Operator precedence gets in the way. (Easily fixed.)
>>> lambda: eggs += lay_eggs()
SyntaxError: can't assign to lambda

2) Assignment is a statement, so you can't do it in a lambda.
>>> lambda: (eggs += lay_eggs())
SyntaxError: invalid syntax

3) Assignment makes it local, so you'll get UnboundLocalError if you
don't declare it nonlocal.
>>> def f():
    eggs += lay_eggs()
>>> f()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    f()
  File "<pyshell#4>", line 2, in f
    eggs += lay_eggs()
UnboundLocalError: local variable 'eggs' referenced before assignment

Hence my previous statement that you need to write the function out of
line, which breaks the switch-ness of the block, and you definitely
need to declare eggs nonlocal. Now, if eggs is a list, you can extend
it with a method (which can be called in an expression), but if your
switch block can only do expressions, it's pretty limited.

ChrisA
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/