Python Best Practices

Chapter 2 of 8 · 5 practices · 3 min · 4-question quiz

Style, formatting and linting

How to make Python code look the same across a team without arguing about it, and the idioms that make it easier to read.

Start: Follow PEP 8 and let a formatter apply it

5 practices in this chapter

  1. 1Follow PEP 8 and let a formatter apply itPEP 8 is the shared style guide for Python. The parts that matter most day to day: PEP 8 itself says consistency within a project matters more than the guide, and consistency within a module matters…
  2. 2Lint in CI and fail the build on new warningsA linter finds bugs that tests miss: unused imports, names that are never defined, mutable default arguments, except blocks that swallow everything. Ruff has over 900 built-in rules and describes…
  3. 3Compare to None with is, and check types with isinstanceTwo comparisons look right and behave subtly wrong: x == None calls the object's __eq__, which a class can override. PEP 8 says to compare singletons like None with is or is not…
  4. 4Use pathlib for paths and name the encoding when you open textString paths joined with + or os.path.join break on Windows and are hard to read. pathlib.Path handles separators and gives you .read_text(), .glob() and .with_suffix() on the path itself.
  5. 5Write docstrings for public functions, classes and modulesType hints say what a function takes and returns. A docstring says why it exists, what it does with edge cases and what it raises. Editors show docstrings on hover, so they are the first…

Check yourself on this chapter

4 questions, right here once you are signed in. Your progress is saved as you read.

Sign up for the quiz