[Tutor] Passing functions as arguments to other functions

boB Stepp robertvstepp at gmail.com
Fri Sep 30 20:46:00 EDT 2016


On Fri, Sep 30, 2016 at 6:55 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, Sep 29, 2016 at 09:43:57PM -0500, boB Stepp wrote:

>> But why does Python require
>> separating the function object from its parameters when it is being
>> passed as an argument to another function?
>
> If you pass the function arguments to the function *first*, then it gets
> evaluated before the second function gets to see it. Let's investigate:
>
> def g(*args):
>     print("Calling function g with arguments {}".format(args))
>     return 999
>
> def f(func, *args):
>     print("f received first argument: {}".format(func))
>     print("f received additional arguments: {}".format(args))
>     return func(*args)
>
>
> Let's try it the right way:
>
> py> f(g, 1, 2, 3)
> f received first argument: <function g at 0xb7ac965c>
> f received additional arguments: (1, 2, 3)
> Calling function g with arguments (1, 2, 3)
> 999
>
>
>
> And the wrong way:
>
> py> f(g(1, 2, 3))
> Calling function g with arguments (1, 2, 3)
> f received first argument: 999
> f received additional arguments: ()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 4, in f
> TypeError: 'int' object is not callable
>
>
>
> Does this help?

Yes.  Thanks, Steve!  Very helpful examples.



-- 
boB


More information about the Tutor mailing list