[Python-ideas] Syntax for passing lambdas to functions

Chris Angelico rosuav at gmail.com
Thu Feb 27 22:24:07 CET 2014


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), and something there's no point in forbidding, but I'm glad
complex targets in general are accepted.

It does allow stupid stuff, though. Check this out:

lst=[10,20,30,40,50] # Any source list

dest=[None]*len(lst)
for i,dest[i] in enumerate(lst): pass

assert dest == lst

I suppose in theory there might be a use for that, but if you want to
talk about things that accidentally work, I'd say this form of list
copy would have to be one of them :)

ChrisA
(Why do I always come up with the stupidest ideas?)


More information about the Python-ideas mailing list