- PEP-8 Style Guide for Python Code
- Explicit is better than implicit
- Do not repeat yourself
- Keep things simple
- Keep things intuitive
- SOLID
- The Twelve-Factor App
- Always prefer code maintainability and readability even if this might sacrifice some performance.
- Google Python Style Guide
- Keep functions and methods ideally less than 25 lines.
- Maintain methods lowest cyclomatic complexity: avoid
if
statements when possible (write branchless code), never use nestedif
. Be Never Nester. - Don't concatenate strings with
+
it's unprofessional, error-prone, slower, and might be confusing, prefer f-string or"".join()
. - The lesser indent your code has, the better.
- Use
isort
, andblack
to format your code. - Use
pylint
, andmypy
to check your code.
- A method signature where the order of arguments "does not matter" (e.g. args are the same type) or the order is obvious is good for positional arguments:
def add(a: float, b: float) -> float: ...
- A method that expects non-interchangeable arguments is a good case to enforce keyword arguments, which will remove any ambiguity or wondering what should come first when calling the method:
def set_token(self, *, domain: str, token: str, expires_in: int) -> None: ...
- For a method around something you can combine positional and keyword arguments, using one positional for "something" and keyword arguments for everything else:
def get_instance(self, instance_id: int, *, include_inactive: Optional[bool] = False) -> T: ...