Reputation: 680
Map not calling the function being passed.
class a:
def getDateTimeStat(self,datetimeObj):
print("Hello")
if __name__ == "__main__":
obj = a()
print("prog started")
data = [1,2,3,4,5]
b = list(map(obj.getDateTimeStat,data))
Expected op on a new line: Hello Hello Hello Hello Hello
Any help will be appreciated....
Upvotes: 12
Views: 15691
Reputation: 70735
You're using Python 3, right? map()
returns an iterator in Python 3, not a list. So use any of the ways to force an iterator to produce its results; for example,
b = list(map(obj.getDateTimeStat,data))
Here I'm running the exact code currently in your question:
class a:
def getDateTimeStat(self,datetimeObj):
print("Hello")
if __name__ == "__main__":
obj = a()
print("prog started")
data = [1,2,3,4,5]
b = list(map(obj.getDateTimeStat,data))
And here's the output:
$ python -V
Python 3.3.2
$ python yyy.py
prog started
Hello
Hello
Hello
Hello
Hello
Show exactly what happens - as I did for you.
Upvotes: 2
Reputation: 298532
Python 3's map
function is lazy, unlike Python 2's map
.
You have to consume it somehow:
for result in map(...):
pass
Non-lazy evaluation version of map in Python3? highlights a few more elegant solutions.
Upvotes: 7
Reputation: 1686
In Python 3, map values are evaluated lazily. That is, each value is only computed when it's needed. You'll find that regardless of what function you use, it won't get called until you ask for the value of that item in the mapped result, whether by using next()
or some other way.
To get what you want, you can do this:
>>> b = map(obj.getDateTimeStat,data)
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Hello
>>> next(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Or this:
>>> b = list(map(obj.getDateTimeStat,data))
Hello
Hello
Hello
Hello
Hello
Or a variety of other things.
Upvotes: 37