Small but big things in Python
1. Use Python 3
In case you missed it: Python 2 is officially not supported as of January 1, 2020. This guide has a bunch of examples that only work in Python 3. If you’re still on Python 2.7, upgrade now.
If you’re on macOS, you can use Homebrew to painlessly upgrade Python.
2. Check for a minimum required Python version
You can check for the Python version in your code, to make sure your users are not running your script with an incompatible version. Use this simple check:
3. Use IPython
IPython is basically an enhanced shell. It’s worth it just for the autocompletion alone, but there is much more. I like it too for all the magic commands that are built-in. Here are a few :
%cd
— to change the current working directory%edit
— to open an editor and execute the code you typed in after closing the editor%env
— to show the current environment variables%pip install [pkgs]
— to install packages without leaving the interactive shell%time
and%timeit
— to time the execution of Python code
4. List Comprehensions
A list comprehension can replace ugly for loops used to fill a list. The basic syntax for a list comprehension is:
[ expression for item in list if conditional ]
A very basic example to fill a list with a sequence of numbers:
And because you can use an expression, you can also do some math:
Or even call an external function:
And finally, you can use the ‘if’ to filter the list. In this case, we only keep the values that are dividable by 2:
Credit-Erik-Jan van Baaren