Learn useful tricks and concepts to write smarter scripts and prevent bad errors in Python.
Use get()
with dictionaries
In Python, dictionaries are collections of data with key-value pairs.
A direct call of any value through its key is one of the most common mistakes in Python. It leads to bad behaviours.
If the key does not exist, the script exits. Endgame! Instead, use the get()
method, it already checks if the key exists:
team = {
"productor": "Lionsgate",
"actor": "Keanu Reeves",
"director": "Chad Stahelski"
}
actress = team.get("bullets", 2000000)
In the above example, I don't have to check if the key "bullets" exists, and the script does not stop. I can even specify a default value.
Sometimes, in tutorials, we write quick and dirty examples with direct calls, but beginners cannot know it's a bad practice.
==
is not is
==
does the same as in any other language. It checks if variables have equal values.
is
checks if two operands refer to the same object. Every time you add a variable in your script, it gets a new "slot" in memory. You can check it with the id()
method:
x = "unknown"
y = "elsewhere"
print(id(x))
print(id(y))
You get:
140476677427376
140476698294128
so :
if (x is y):
print("wtf")
else:
print("x is not y")
displays:
x is not y
However, Python has internal optimisations:
x = 111
y = 111
print(id(x))
print(id(y))
if (x is y):
print("wtf")
else:
print("x is not y")
will display something like that:
4457849408
4457849408
wtf
That's normal. Python uses the same memory slot for integers less than 256.
Therefore, be extra careful with the is
keyword.
Do not switch between tabs and spaces
This one is especially not allowed in Python3. If you have only one command line in your code block, using spaces instead of tabs won't produce any error.
Choose whatever style you want, but keep consistency. Otherwise, you will get errors sooner or later.
If it's not your code, please consider reformatting it. Most of the time, the IDE (integrated development environment) has options such as "convert tabs into spaces" for that.
Reserved keywords
All languages have reserved keywords. To get the full list just run the following in the Python interpreter:
help("keywords")
Your IDE is useful here too. Most of the time, if it supports Python (which is likely), reserved keywords have a specific colour.
Use try/except/else and finally
It's always a better idea to try code and catch errors instead of assuming everything will work as expected.
In Python, you can use exceptions like that:
answer = input()
try:
answer = 111/int(answer)
except:
print("Error, please check your input and use a positive number")
else:
print("The answer is", answer)
finally:
print("That's all folks!")
The keyword "finally" always displays, even if you get exceptions.
Use shorter if statements
Instead of writing:
if myvar == 9 or myvar ==1 or myvar == 7
you can do the following:
if myvar in [9,1,7]
It's faster, and the code is more readable.
Follow guidelines and standards
Of course, you can write your stuff, but guidelines and code standards are the easiest ways, especially if you are a beginner.
In Python, you can use PEP 8 Style Guide. It's a set of rules with Dos and Don'ts.
For example, with PEP8 styles, you cannot use tabs to indent your code. Instead, you use four spaces per each indent.
Besides, it's excellent if you want to contribute.
Write Object Oriented code (OOP)
OOP is a paradigm. It goes beyond any programming/scripting language.
Writing class in Python might look like this:
class Calculation:
"""An example of Python class"""
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
print(self.num1 + self.num2)
calc = Calculation(36, 37)
calc.add()
Import libraries
Any module can access other modules with the import
keyword.
Libraries are handy; for example, if you want to use Python for machine learning, you will probably use Numpy.
But, don't use import like the following:
from os import *
mkdir("existenz")
Instead, do this:
# Standard library imports
import os
try:
os.mkdir("existenz")
except:
print("existenz exists")
else:
print("existenz created")
finally:
print("\\o/")
The first will import all objects from the os package, which can lead to unexpected errors such as naming conflicts.
Besides, you can import third-party and local packages. For them, I recommend using aliases:
import foo as bar
print(bar)
Note that it's possible to use relative paths to import libraries, but, IMHO, it's not a good practice. Pep8 discourages the use of relative paths in imports, and Python3 removed support for implicit relative imports.
Wrap up
I hope those tips and concepts will help you write better Python code. Indeed, it's not an exhausting list, do not hesitate to share your tricks in the comment section below ;)
Top comments (12)
Good stuff. An addition could be instead of just doing
โฆ = input()
, we add a useful message e.g.โฆ. = input("How many Ship do you need to learn C? ")
๐You state "Write Object Oriented code".
You should learn it, and learn when to use it or not. Sometimes a function is all you need.
totally agree with you on that point
as an idea for exercide - instead of a class with methods, write a dataclass and functions that operate on it, see what is cleaner and where would you prefer either
Great article.
import pandas as np
(seen on twitter)
Thanks Julien! Maybe you can write your next post about recommended code layout and importing from local files? This is super weird with Python IMHO.
good idea, noted!
Note that
is None
is idiomatic check for None, probably makes a good additionCool stuff :)
Had no idea about the first point :D
You mention "Use shorter if statements". I get the sentiment but use a set literal rather than the list as it is better for such lookups, in general.
There is a view, often debated though, that the more if's you have is code, the less is the quality (eg flags in fucntions, avoidable branching, etc)
Some comments have been hidden by the post's author - find out more