Skip to content

Latest commit

 

History

History
93 lines (60 loc) · 2.72 KB

03-the-style.md

File metadata and controls

93 lines (60 loc) · 2.72 KB

Python style

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

  • map is builtin.
  • import functools for some functional tooling
  • itertools
  • Use a lib like toolz or funcy for more functional tools
  • lambda are 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