Hello folks! 馃憢
Python comes with a lot of cool and helpful modules, data types, functions, which may not be very well known.
In this series, we are going to see some of the lesser known built-ins and standard libraries that I came across in my time of doing Python.
We will look into the details, real-life examples, nuances, internal workings, and some caveats or gotchas as well.
Of course, there are still quite some that I haven’t had the chance to deal with, and some that might be too common; let’s figure out which ones to include, as we move ahead in the series.
So, let’s get straight to it! 馃殌
Intro In this post, we will look at the groupby function from the itertools module.
The itertools.groupby function groups consecutive elements from an iterable. It accepts an iterable and an optional callable key that computes a key value for each element. It returns an iterator that yields tuples of (key, group), where group itself is an iterator over the consecutive elements that share that key value. If key is not specified or passed as None, then the value of each element is used as key value.
...
Intro In this post, we will look at the defaultdict datatype from the collections module.
The collections.defaultdict is a subclass of the built-in dict that accepts a callable (default_factory) during its initialization. Then, when you try to access a key in the initialized object, it does a regular dict lookup to fetch the key鈥檚 value. If the key is missing, it calls the default_factory that generates a value for the key requested. This key-value pair is then stored in the dict and the value is returned.
...
Intro In this post, we will look at the partial function in the functools module.
The functools.partial function accepts a callable, with arguments (positional and keyword), and returns a partial object that has not yet executed the callable. When this partial object is called, it then passes the arguments to the callable and returns the output. The idea is to have an object that can store even some of the arguments required by the callabel, such that it can be executed in the future. Think of it like taking the callable, with any arguments that you can pass, and then freezing it for a later point.
...