Python style
June 1, 2021 · View on GitHub
Review first
See at the end of 02-the-language
Readability first
Python code reads and should read very much like pseudo code.
“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.”
― Antoine de Saint-Exupéry
Avoid classes
Avoid heavy OOP stuff
- There are no private variables.
- Avoid factories.
- Avoid mixins.
- Avoid more than one layer of inheritance.
Avoid using magic
Explicit is better than implicit
Python is a very dynamic language. There is almost no limit to your imagination. But with great power comes great responsibility: you got to be careful about how far you go with introducing magic in your code. Take inspiration from Golang, which has almost no magic at all!
Embrace flexibility
Avoid strict typing, prefer duck typing
getattr and hasattr.
Ask for forgiveness, not for permission
Avoid long names
class AbstractToasterFactoryClass:
pass
Avoid globals
Globals are:
- Difficult to debug (anything can modify them)
- Difficult to reuse outside the library
Avoid using too many dependencies
The standard library is very complete.
The State of the Octoverse 2020 shows that there are far less dependencies in Python projects:
683 median transitive dependencies for npm followed by PHP (70), Ruby (68), and Python (19). All of which can become impacted by one security vulnerability.
Functional programming in Python
mapis builtin.import functoolsfor some functional toolingitertools- Use a lib like
toolzorfuncyfor more functional tools lambdaare a bit annoying, because they're single line.- Decorators are a super useful pattern and help understand how dynamic Python is
Python lacks some functional features:
- Immutable by default
- True anonymous functions
- Tail recursion