Syntax Suggestion: Pass Function Definition as Argument

Antoon Pardon antoon.pardon at vub.be
Thu Nov 7 09:32:37 EST 2019


On 7/11/19 14:36, Stephen Waldron wrote:
> Hi, I'm new to the group and to Python, so forgive me if I make any faux-pas here. As I can tell, the only way to pass a function as an argument is to reference its name as follows:
>
> def foo1(message):
>     print(message)
>
> def foo2(foo, message):
>     print("Your function says:")
>     foo(message)

No that is not true. "map" is a function that takes a function as its
first argument. But I can do the following if I want to produce the
inverses of a list of numbers.

    from operator import truediv
    from functools import partial

    ls = range(1, 11)

    for x in map(partial(truediv, 1), ls):
        print(x)

In the code above "partial(truediv, 1)" will produce a function that
will inverse its argument and I don't need to give this function a name
to pass it as an argument in an other function.

-- 
Antoon Pardon.


More information about the Python-list mailing list