Python · Chapter 45 of 45

Python Best Practices

Small habits make a big difference. Follow PEP 8, write short functions, use meaningful names, and add tests.

Embrace 'The Zen of Python' — type `import this` to read it.

Do

Use virtual environments. Add type hints. Handle exceptions specifically. Write docstrings. Format with `black`, lint with `ruff`.

Don't

Don't use bare `except:`. Don't use mutable default args. Don't over-use inheritance. Don't optimise before profiling.

Example 1 (python)
# BAD
def d(x, y=[]):
    y.append(x); return y

# GOOD
def d(x, y=None):
    if y is None: y = []
    y.append(x); return y

Never use mutable defaults.

Example 2 (python)
import this  # displays The Zen of Python
Output
The Zen of Python, by Tim Peters...

A short manifesto every Pythonista should read.

Key points

  • Follow PEP 8 (style guide).
  • Format with `black`, lint with `ruff`.
  • Small functions, clear names.
  • Write tests as you go.
💡 Note: Readability counts more than cleverness. If a coworker can't understand your code in 60 seconds, refactor it.

📝 Quick Quiz

1. The Python style guide is:

2. A popular Python formatter is:

3. Which is a Python anti-pattern?