How to make your code Pythonic?
To make your Python code Pythonic, you should follow 2 coding style guidelines: PEP 8 and PEP 20. Let’s dive into them now!
PEP 8
- PEP 8 is about guidelines for
- Code layout
- Whitespace
- Naming conventions
- Other similar style topics
- Take the following example, a file
pythonic.py
import math, os
def printer(name,message):
print(f"You have a new message from {name}")
print(f"{message}")
printer(name="Peter", message='Hi')
- To check PEP8, you can use
pycodestyle
tool in command line
pycodestyle pythonic.py
pythonic.py:1:12: E401 multiple imports on one line
pythonic.py:3:1: E302 expected 2 blank lines, found 1
pythonic.py:3:17: E231 missing whitespace after ','
- To do PEP8 code automatic reformatting, you can use autopep8
autopep8 --in-place pythonic.py
PEP 20
➜ ~ python3
Python 3.7.13 (default, Oct 11 2022, 09:28:42)
[Clang 14.0.0 (clang-1400.0.29.102)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>>
Beautiful is better than ugly
Explicit is better than implicit
from math import sin
def sin():
print("Your sin function logic")
Simple is better than complex
Complex is better than complicated
Flat is better than nested
Sparse is better than dense
Readability counts
# Low readability code
sn = ["Bob", "Jack", "Harry"]
for n in sn:
print(n)
# Hide readability code
student_names = ["Bob", "Jack", "Harry"]
for name in student_names:
print(name)
Special cases aren’t special enough to break the rules Although practicality beats purity
Errors should never pass silently Unless explicitly silenced
- Error is passed siliently
a = 1
b = 0
try:
c = a / b
except:
pass
- Error is handled and logged
a = 1
b = 0
try:
c = a / b
except ZeroDivisionError:
print("Can not divide by zero!")
In the face of ambiguity, refuse the temptation to guess
There should be one, and preferably only one way to do it Although that way may not be obvious at first unless you’re Dutch
# Using the % operator
programming_language = "Python"
print("The Zen of %s" % programming_language)
# Using the .format() method
print("The Zen of {}".format(programming_language))
# Using f-string
print(f"The Zen of {programming_language}")
Now is better than never Although never is often better than right now
If the implementation is hard to explain, it’s a bad idea If the implementation is easy to explain, it may be a good idea
Namespaces are one honking great idea – let’s do more of those!
def chase():
# Good namespacing
import cartoon.models.cat as cat
import cartoon.models.dog as dog
dog.chase(cat)
cat.chase(mouse)
There should be 20 guidelines for PEP 20, but you can see that there are just 19 of them, the 20th guideline is up to you to define!