Can Python's map function call object member functions?

Question:

I need to do something that is functionally equivalent to this:

for foo in foos:
    bar = foo.get_bar()
    # Do something with bar

My first instinct was to use map, but this did not work:

for bar in map(get_bar, foos):
    # Do something with bar

Is what I’m trying to accomplish possible with map? Do I need to use a list comprehension instead? What is the most Pythonic idiom for this?

Asked By: Josh Glover

||

Answers:

You want operator.methodcaller(). Or, of course, a list or generator comprehension.

Either with lambda:

for bar in map(lambda foo: foo.get_bar(), foos):

Or simply with instance method reference on your instance’s class:

for bar in map(Foo.get_bar, foos):

As this was added from a comment, I would like to note that this requires the items of foos to be instances of Foo (i.e. all(isinstance(foo, Foo) for foo in foos) must be true) and not only as the other options do instances of classes with a get_bar method. This alone might be reason enough to not include it here.

Or with methodcaller:

import operator
get_bar = operator.methodcaller('get_bar')
for bar in map(get_bar, foos):

Or with a generator expression:

for bar in (foo.get_bar() for foo in foos):
Answered By: Dan D.

This modified code will work:

for bar in map(lambda f: f.get_bar(), foos):
# Do something with bar

You provide lambda function here. Simply providing get_bar doesn’t work because it is accessible only through an instance of class (f.get_bar()), never by itself.

Answered By: AlexD

You can use lambda

for bar in map(lambda foo: foo.get_bar(), foos):
    # Do something with bar
Answered By: Jarek Przygódzki

I think the cleanest way is to forgo the for-loop completely and use a list comprehension:

bars = [foo.get_bar() for foo in foos]

This answer is close to some other answers but differs in that the list is actually returned and not used in the subsequent loop. Depending on what you do with bars, you may be able to use a list comprehension there to.

I don’t think the map function with lambdas are particulary readable, besides the overhead for map is considerable.

Answered By: nluigi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.