Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Python's map function call object member functions?

Tags:

python

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?

like image 709
Josh Glover Avatar asked Oct 13 '11 07:10

Josh Glover


People also ask

What does map () do in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.

How do you iterate through a map object in Python?

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc.

How do you call a function object in Python?

To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.

What does map () return in Python?

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)


1 Answers

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): 
like image 133
Dan D. Avatar answered Oct 12 '22 09:10

Dan D.