by Adam Goldschmidt
Awesome Python modules you probably aren’t using (but should be)
Python is a beautiful language, and it contains many built-in modules that aim to help us write better, prettier code.
Throughout this article, we will use some lesser-known modules and methods that I think can improve the way we code - both in visibility and in efficiency.
I believe that some of you already know the more popular
namedtuple from the
collections module (if you don't - check it out), but since Python 3.6, a new class is available in the
NamedTuple. Both are designed to help you quickly create readable immutable objects.
NamedTuple is actually a typed version of
namedtuple, and in my opinion, is much more readable:
Efficient arrays of numeric values. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. — Python docs
When using the
array module, we need to instantiate it with a typecode, which is the type all of its elements will use. Let's compare time efficiency with a normal list, writing many integers to a file (using
pickle module for a regular list):
14 times faster. That’s a lot. Of course it also depends on the
pickle module, but still - the array is way more compact than the list. So if you are using simple numeric values, you should consider using the
I got to use the
combinations method this week and I thought I'd share it. This method takes an iterable and an integer as arguments, and creates a generator consisting of all possible combinations of the iterable with a maximum length of the integer given, without duplication:
A quick and beautiful way of creating a dict with default values:
Last but not least - the
As you may or may not know, Python compiles source code to a set of instructions called “bytecode”. The
dis module helps us handle these instructions, and it's a great debugging tool.
Here’s an example from the Fluent Python book:
We got an error — but the operation still succeeded. How come? Well, if we look at the bytecode (I added comments near the important parts):
Before you go…
If you enjoyed this article, please hold down the clap button 👏 to help others find it. The longer you hold it, the more claps you give!
And do not hesitate to share more Python hidden gems in the comments below.