What is exactly passed as an argument if we pass Python function name?

Question:

Recently I was describing my code to my Uni teacher, it was something like this:

def f(x):
    return x*x

def map_list(function, list):
    return [function(element) for element in list]

map_list(f, [1,2,3])

and I told that in map_list(f, [1,2,3]), f argument is a pointer to the function, which is obviously wrong, as there are no pointers really in PYthon. I was trying to figure it out, but I couldn’t find any clear answer. So, what is it? Reference, object, or something else?

Thanks in advance.

Asked By: z0idb3rg

||

Answers:

Functions are first-class objects in python and as such you can pass them into functions and place them in lists, dictionaries etc. They are getting passed as object references.

Answered By: bhristov

What you pass is a name which is bind to an object.
You can have several names bind to the same object, as in this example:

x = []
y = x # x and y are two names bind to the same object

If you call a function with a parameter you create another name (the name of the argument) bind to the passed object.

In your case the function map_list accepts everything that is callable with (). This means you can pass anything which has implemented the __call__() method. This is of course also the case for a function.

Answered By: Alexander Kosik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.