Search code examples
python-3.xgenerator

Passing functions without () into map/filter/reduce


In Python3.X, when passing methods into Map/Filter/Reduce, why is it done without '()'? Does this apply to all generators?

This is probably a simple question but I can't find a clear answer in docs. I'm hoping to understand the reasons rather than just "memorizing" syntax.

e.g.

map(str.upper, ['a', 'b', 'c']) #this works 
vs 
map(str.upper(), ['a', 'b', 'c']) #this gives an error

Solution

  • This is confusing at first, especially when you come from other programming languages. In Python the functions are objects and you can pass them along without invoking them. Check below example:

    def func():  # function definition
        print("func was invoked")
    
    
    a = func  # assign func object (without invoking it)
    print(a, type(a))
    
    
    a()  # invoking the function
    

    map will use this function object to invoke the function for each item in the iterable.