jhourback
jhourback

Reputation: 4571

Avoiding unncessary use of lambda for calls to object methods

Consider the following code, which simply calls a method on each member of a list:

class Demo:
    def make_change(self):
        pass

foo = [Demo(), Demo(), Demo()]
map(lambda x: x.make_change(), foo)

Is there a way to accomplish this without the long-winded lambda syntax? For example, in Scala, something similar to map(_.make_change(), foo) works. Does Python have an equivalent?

Upvotes: 1

Views: 172

Answers (3)

pillmuncher
pillmuncher

Reputation: 10162

I'm with gnibbler on the pythonicity. Apart from that, this is also possible:

map(Demo.make_change, foo)

It has problems, though:

class Demo(object):
    def __init__(self):
        self.x = 1
        self.y = 2
    def make_change(self):
        self.x = 5

class SubDemo(Demo):
    def make_change(self):
        self.y = 7

d = Demo()
s = SubDemo()
map(Demo.make_change, [d, s])

assert d.x == 5 and s.y == 7 # oops!

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304375

It's not very pythonic to use map just for side-effects

so why not

for item in foo:
    item.make_change()

This will run faster than using map

you can put it on one line if you insist, but I wouldn't

for item in foo:item.make_change()

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

operator.methodcaller('make_change')

Upvotes: 2

Related Questions