Member-only story
5 Advanced Python Function Concepts Explained With Examples
Lambdas, decorators, partials, and more
If your program is a factory, functions are its workers that maneuver the machinery to make your program run. In a typical factory, there are different types of workers tasked with varied jobs. Correspondingly, your program should be versatile in terms of its functions. To write robust functions, your coding arsenal should include the necessary tools to allow you to equip your program with the best workers.
In this article, I’d like to explain five advanced concepts related to functions in Python. Before we start the discussion, let’s assume that we understand the basic form of Python functions as annotated in the code snippet below:
1. Undetermined Arguments (*args and **kwargs)
When we define functions, we can have both positional and keyword arguments. Positional arguments are parsed by their positions, whereas keyword arguments are parsed by their argument names (i.e. the keywords or identifiers). Let’s look at the signature of the built-in print
function:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The objects
argument is positional (we’ll talk about the asterisk shortly). All other arguments have their unique identifiers (e.g. sep
, end
), and they’re thus keyword arguments. As a side note, we can have different orders when passing keyword arguments because they’re parsed by their identifiers. However, positional arguments are strictly parsed by the position. Some examples are shown below:
One thing that you may have noticed is that I passed two strings for the objects
argument. That’s possible just because there is an asterisk…