Skip to content
BIASED

Closures and decorators

Block 1 of 8~2 min

A function is an object too

The topic The data model showed that a call x(...) is one more protocol: Python looks up __call__ on the type of x. An instance of a class with __call__ behaves like a function that remembers something between calls, such as a factor or a counter. Python's own functions are objects too, of type function. This topic shows that they can remember state without any class, and how that memory is used to wrap one function in another.

def creates a function object and binds a name to it, like any assignment in the topic Values, types and names. The object can then be bound to other names, stored in containers and passed to other functions:

def square(x):
    """Return x squared."""
    return x * x
 
f = square
print(f(7), f is square, f.__name__, f.__doc__)
print(type(square))
ops = {"sq": square, "neg": lambda x: -x}
print(ops["neg"](5))
print(sorted(["pear", "fig", "banana"], key=len))
49 True square Return x squared.
<class 'function'>
-5
['fig', 'pear', 'banana']

f = square copies nothing. Both names refer to one object, and its __name__ is the name that def gave it. A lambda is the expression form of def, limited to a single expression, and it creates the same kind of object. A function that takes or returns functions, as sorted takes key=len, is called a higher-order function.

A function object carries more than its code. __code__ holds the compiled code and the names of its variables. __defaults__ holds the default values, computed once when def ran; that is the source of the mutable-default trap from the topic Functions. A function defined inside another function has one more attribute, __closure__, and the rest of the topic grows out of it.

Answers are saved on the server and tied to this browser until you sign in.