15
Lesson 19 of 44

Advanced functions and decorators

Take your functions to the next level. In this lesson you will learn how to receive a variable number of arguments with *args and **kwargs, how to pass and return functions, how to create closures with nonlocal, how to write decorators (also with parameters) and how to use functools tools such as reduce, partial and cache.

  • 5 theory articles
  • 10 practice exercises
Start lesson

Fundamentals concepts 5

Variable arguments: *args and **kwargs

Until now, each function received a fixed number of arguments. But print accepts as many as you want, and so does max(3, 9, 5) …

Theory
Read more

Functions as values and closures

In Python functions are objects , just like numbers or texts: they can be stored in variables, passed as arguments and returned…

Theory
Read more

Decorators

A decorator is a function that receives another function and returns an improved version of it, without touching its code. It is…

Theory
Read more

Decorators with parameters

Sometimes you want to customize the decorator: "repeat the function 3 times", "warn only if it takes more than 1 second". For…

Theory
Read more

functools and common mistakes

The functools module gathers tools for working with functions. These are the three most useful ones.

Theory
Read more

Practice exercises 10

Sum of any amount of numbers

Create a Python program with a function that adds as many numbers as it receives, using *args .

Exercise Easy
Solve it

Grades summary

Create a Python program with a function that receives a variable number of grades and returns several results at once.

Exercise Easy
Solve it

Record with keyword arguments

Create a Python program with a function that receives any amount of keyword arguments using **kwargs .

Exercise Easy
Solve it

Final price with default values

Create a Python program with a function that computes a final price and has optional parameters with a default value.

Exercise Easy
Solve it

Multiplier factory

Create a Python program with a function that returns another function .

Exercise Easy
Solve it

Independent counters

Create a Python program that uses a closure with nonlocal to have several counters that do not get mixed up.

Exercise Medium
Solve it

Decorator that logs calls

Create a Python program with your first decorator : a function that wraps another one to add behaviour to it.

Exercise Medium
Solve it

Decorator that counts calls

Create a Python program with a decorator that keeps track of how many times a function has been called.

Exercise Medium
Solve it

Decorator with a parameter

Create a Python program with a decorator that receives a parameter: it needs three levels of functions.

Exercise Medium
Solve it

Reduce a list to one value

Create a Python program that uses functools.reduce to combine all the elements of a list into a single value.

Exercise Medium
Solve it