[Pythonmac-SIG] Lambdas and closures

Chris Weisiger cweisiger at msg.ucsf.edu
Wed Aug 10 18:46:59 CEST 2011


On Wed, Aug 10, 2011 at 9:38 AM, Aahz <aahz at pythoncraft.com> wrote:
> On Wed, Aug 10, 2011, Chris Weisiger wrote:
>>
>> There's probably a more generic mailing list I could send this to, but
>> I'm on too many lists as it is...hope y'all don't mind.
>>
>> Anyway, I often find myself in the situation of "I have a list of
>> objects. I want to make a corresponding list of functions that operate
>> on those objects". So I write up something like this:
>>
>> funcList = []
>> for item in objectList:
>>     funcList.append(lambda input: item.actOn(input))
>
> Why can't you do:
>
> for item in object_list:
>    func_list.append(item.act_on)
>

Sorry, my example was poor. A more realistic example:

for item in objectList:
    funcList.append(lambda event: item.actOn(event.GetInt()))

Otherwise, you're right, the lambda isn't actually doing anything there. Whoops.

> (Notice who I change the names to match PEP8.)

Fair for one-off examples like on these mailing lists; I'm not that
familiar with PEP at the moment because I'm far more worried about
enforcing consistency of any kind on the code I maintain, and that
happened to mean going with camelCase. The rules of coding style, in
order of importance, are 1) suit the need; 2) match the rest of the
code; 3) match internal style guides; 4) match external style guides.
PEP is mostly for when you're starting a new project and need to
decide on a style (or in that rare case when you get to overhaul an
existing project's style). Of course things are made worse in my case
by the extensive use of libraries that use CamelCase (wx) and whatever
you call the foo_bar style (numpy), so I'm screwed no matter what. :)

-Chris


More information about the Pythonmac-SIG mailing list