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 it5 practices in this chapter
- 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…
- 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,
exceptblocks that swallow everything. Ruff has over 900 built-in rules and describes… - 3Compare to None with is, and check types with isinstanceTwo comparisons look right and behave subtly wrong:
x == Nonecalls the object's__eq__, which a class can override. PEP 8 says to compare singletons likeNonewithisoris not… - 4Use pathlib for paths and name the encoding when you open textString paths joined with
+oros.path.joinbreak on Windows and are hard to read.pathlib.Pathhandles separators and gives you.read_text(),.glob()and.with_suffix()on the path itself. - 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.