[Python-ideas] Syntax for passing lambdas to functions
Andrew Barnert
abarnert at yahoo.com
Thu Feb 27 23:26:11 CET 2014
On Feb 27, 2014, at 13:24, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, Feb 28, 2014 at 8:14 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>>> class A: ...
>>> a = A()
>>> l = [0]
>>>
>>> for a.x in [1, 2, 3]: ...
>>> for l[0] in [1, 2, 3]: ...
>>
>> I wonder whether that is deliberate feature, or an accident of the way
>> the syntax works. It does seem to be pretty useless though -- why are
>> you using an attribute or list as a loop variable?
>
> I would say it's no accident that the for loop can accept any lvalue.
> That's how we can do this, which I'm sure you'll agree is *extremely*
> useful:
>
> for x,y in [(1,2), (3,4), (5,6)]: ...
>
> Assigning to the tuple works beautifully there (especially with
> enumerate or zip). Being able to assign to other complex targets is a
> bonus that you'll probably never come across (I can imagine someone
> might have a use for "for self.blah in ...", but can't concoct any
> right now)
Something I've seen in real code (not _good_ code, but actually deployed):
for self.index in range(len(self.values)):
if self.values[self.index] == spam:
break
else:
self.index = None
Apparently someone didn't want to catch the exception from list.index. (Or, more likely, they were trying to write C code in Python.)
More information about the Python-ideas
mailing list