Despite not being a pure functional language, a lot of praise that python receives are for features that stem from functional paradigms. Many are second nature to python programmers, but over the years I have seen people miss out on some important features. I gathered a few, along with examples, to give a brief demonstration of the convenience they can bring.
Replace if/else
with or
With values that might be None
, you can use or
instead of if/else
to provide a default. I had used this for years with Javascript, without knowing it was also possible in Python.
|
|
Above snippet can shortened to this:
|
|
Pattern Matching and Unpacking
The overdue arrival of match
to python means that so many switch
style statements are expressed instead with convoluted if/else
blocks. Using match
is not even from the functional paradigm, but combining it with unpacking opens up new possibilities for writing more concise code.
Let’s start by looking at a primitive example of unpacking. Some libraries have popularised use of [a, b] = some_fun()
, but unpacking in python is much powerful than that.
|
|
Matching Lists
Just look at the boost in readability when we are able to name and extract relevant values effortlessly:
|
|
|
|
Matching Dictionaries
Smooth, right? We can go even further with dictionaries. This example is not necessarily better than its if/else
counterpart, but I will use it for the purpose of demonstrating the functionality.
|
|
Matching Dataclasses
Let’s write a function that does a primitive calculation of an estimated number of days for shipment
|
|
|
|
Comprehensions
List comprehensions get their deserved spotlight, but I’ve seen cases where dictionary comprehension would’ve cut multiple lines. You can look at examples on this page on python.org