30 Python Best Practices, Tips, and Tricks by Erik Van Baaren Python Land Medium
30 Python Best Practices, Tips, and Tricks by Erik Van Baaren Python Land Medium
Here are 30 Python best practices, tips, and tricks. I’m sure they’ll help you
procrastinate your actual work, and still learn something useful in the process.
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.
3. Use IPython
Screenshot by author
IPython is basically an enhanced shell. It’s the core of the very popular Jupyter
Notebook. 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 :
%edit — to open an editor and execute the code you typed in after closing the
editor
%pip install [pkgs] — to install packages without leaving the interactive shell
4. List Comprehensions
A list comprehension can replace ugly for loops used to fill a list. The basic syntax for a
list comprehension is:
And because you can use an expression, you can also do some math:
1 def some_function(a):
2 return (a + 5) / 2
3
4 my_formula = [some_function(i) for i in range(10)]
5 print(my_formula)
6 # [2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
And finally, you can use the ‘if’ to filter the list. In this case, we only keep the values
that are dividable by 2:
For a more thorough explanation, head over to this list comprehension tutorial.
1 import sys
2
3 mylist = range(0, 10000)
4 print(sys.getsizeof(mylist))
5 # 48
It’s because the range function returns a class that only behaves like a list. A range is a
lot more memory efficient than using an actual list of numbers.
You can see for yourself by using a list comprehension to create an actual list of
numbers from the same range:
1 import sys
2
3 myreallist = [x for x in range(0, 10000)]
4 print(sys.getsizeof(myreallist))
5 # 87632
1 def get_user(id):
2 # fetch user from database
3 # ....
4 return name, birthdate
5
6 name, birthdate = get_user(4)
This is alright for a limited number of return values. But anything past 3 values should
be put into a (data) class.
you can compare data classes because __eq__ is implemented for you
you can easily print a data class for debugging because __repr__ is implemented as
well
If you think this is useful, read this Python data class tutorial with lots of examples. It’s
also good to know there’s also a more advanced version of data classes offered by
Python Attrs.
1 a = 1
2 b = 2
3 a, b = b, a
4 print (a)
5 # 2
6 print (b)
7 # 1
If there are overlapping keys, the keys from the first dictionary will be overwritten.
To split on whitespace, you actually don’t have to give split any arguments. By default,
all runs of consecutive whitespace are regarded as a single whitespace separator by
split . So we could just as well use mystring.split() .
If you were wondering why it’s not mylist.join(" ") — good question!
It comes down to the fact that the String.join() function can join not just lists, but any
iterable. Putting it inside String prevents implementing the same functionality in
multiple places.
13. Emoji
1 import emoji
2 result = emoji.emojize('Python is :thumbs_up:')
3 print(result)
4 # 'Python is 👍'
5
6 # You can also reverse this:
7 result = emoji.demojize('Python is 👍')
8 print(result)
9 # 'Python is :thumbs_up:'
Visit the emoji package page for more examples and documentation.
a[start:stop:step]
Start , stop and step are optional. If you don’t fill them in, they will default to:
0 for start
1 for step
1 revstring = "abcdefg"[::-1]
2 print(revstring)
3 # 'gfedcba'
4
5 revarray = [1, 2, 3, 4, 5][::-1]
6 print(revarray)
7 # [5, 4, 3, 2, 1]
You can use the following code to display the image from your Python code:
Pillow can do a lot more than displaying the image. It can analyze, resize, filter,
enhance, morph, etcetera. See the documentation for all its features.
map(function, something_iterable)
So you give it a function to execute, and something to execute on. This can be anything
that’s iterable. In the examples below I’ll use a list.
1 def upper(s):
2 return s.upper()
3
4 mylist = list(map(upper, ['sentence', 'fragment']))
5 print(mylist)
6 # ['SENTENCE', 'FRAGMENT']
7
8 # Convert a string representation of
9 # a number into a list of ints.
10 list_of_ints = list(map(int, "1234567"))
11 print(list_of_ints)
12 # [1, 2, 3, 4, 5, 6, 7]
Take a look at your own code and see if you can use map() instead of a loop
somewhere! Many Python programmers will prefer to use list comprehensions where
possible, though, since it is considered to be more pythonic.
1 mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
2 print (set(mylist))
3 # {1, 2, 3, 4, 5, 6}
4
5 # And since a string can be treated like a
6 # list of letters, you can also get the
7 # unique letters from a string this way:
8 print (set("aaabbbcccdddeeefff"))
9 # {'a', 'b', 'c', 'd', 'e', 'f'}
1 test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
2 print(max(set(test), key = test.count))
3 # 4
Do you understand why this works? Try to figure it out for yourself before reading on.
max() will return the highest value in a list. The key argument takes a single
argument function to customize the sort order, in this case, it’s test.count. The
function is applied to each item on the iterable.
test.count is a built-in function of list. It takes an argument and will count the
number of occurrences for that argument. So test.count(1) will return 2 and
test.count(4) returns 4.
So what we do in this single line of code is take all the unique values of test, which is
{1, 2, 3, 4} . Next, max will apply the list.count function to them and return the
maximum value.
In [1]: 3 * 3
Out[1]: 9
In [2]: _ + 3
Out[2]: 12
This works in the Python shell (REPL) too. In addition, the IPython shell allows you to
use Out[n] to get the value of the expression In[n] . E.g., Out[1] would give us the
number 9 in the example above.
22. Quickly create a web server
You can quickly start a web server, serving the contents of the current directory:
python3 -m http.server
This is useful if you want to share some stuff with a co-worker or want to test a simple
HTML site. Don’t use it for anything that comes close to a production system, though.
I prefer another method, which concatenates multiple lines together, allowing you to
format your code nicely. The only downside is that you need to explicitly put in
newlines:
As an example:
You can do so much cool stuff with this library. I’ll limit the examples to just this one
that I found particularly useful: fuzzy parsing of dates from log files and such.
Just remember: where the regular Python datetime functionality ends, python-dateutil
comes in!
In Python 2, the division operator ( / ) defaults to an integer division, unless one of the
operands is a floating-point number. So you have this behavior:
# Python 2
5 / 2 = 2
5 / 2.0 = 2.5
Python 3
5 / 2 = 2.5
5 // 2 = 2
For the complete motivation behind this change, you should read PEP-0238.
30. Charset detection with chardet
You can use the chardet module to detect the charset of a file. This can come in very
useful when analyzing big piles of random text. Install with:
You now have an extra command-line tool called chardetect, which can be used like
this:
chardetect somefile.txt
somefile.txt: ascii with confidence 1.0
You can also use the library programmatically, check out the docs.
That’s it! 30 tips, tricks, and best practices. I hope you enjoyed them as much as I
enjoyed creating the list. If you have anything to add, feel free to leave a comment!
Get updated on our best articles. No spam. No selling of your data. Promised! Take a look.
Your email
By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information
about our privacy practices.