12

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
  • 670
  • 2
  • 9
  • 23

3 Answers3

36

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.

Pandu
  • 1,606
  • 1
  • 12
  • 23
  • Thanks for you comment... The problem I have is for some reason the function is nt getting called which is weird! – Ankit Solanki Oct 14 '13 at 09:47
  • 1
    It 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. – Pandu Oct 15 '13 at 02:35
7

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.

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Hey 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 Oct 14 '13 at 09:42
2

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.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132