Python: Map calling a function not working
Solution 1
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.
Solution 2
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.
Solution 3
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))
Later
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.
Ankit Solanki
Updated on June 21, 2022Comments
-
Ankit Solanki almost 2 years
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....
-
Ankit Solanki over 10 yearsHey Thanks for your reply, I have edited the function above now, I was using a list to catch the iterator values. Whats happening here is the function is not getting called at all!
-
Ankit Solanki over 10 yearsThanks for you comment... The problem I have is for some reason the function is nt getting called which is weird!
-
Ankit Solanki over 10 yearsThanks for you comment... The problem I have is for some reason the function is nt getting called which is weird!
-
Pandu over 10 yearsIt will get called if you try to access the values in the map. I suggest you read up on lazy evaluation to get what's going on.