Write a python style guide document
Several things have popped up during review of the series to add type hint annotations to the qapi generator (and formalize other stylings while we're at it); while adding information to the commit messages is helpful to those doing extremely targeted spelunking, a style guide explaining certain decisions might be best for centralized reference in the future.
Some points to cover (not complete, not final, not authoritative, pending discussion, etc)
-
Mypy habits:
- Using immutable instead of mutable literals whenever appropriate (prefer tuple to list)
- Using the most abstracted type for function input (use Iterable instead of List when possible.)
- Using the most concrete type for function return
- Preferring NamedTuple or full classes for aggregating typed data
- Using
@dataclassin preference to full classes when 3.7 is available to us - Using
TypedDictas a type-safe alternative to "dictly-typed" data when 3.8 is available to us
- Using
- prefer
@classmethodto@staticmethodin almost all cases unless you are certain you wish to actively prohibit subclassing - Default to following LSP unless you have a good reason not to. Only extend, never rewrite, init arguments.
- Augment classes with
@classmethodconstructors when wanting to provide LSP-incompatible constructors. - use
assert isinstance(x, MyType), "Exception/Diagnostic msg"to downcast a type when it should be impossible by the logic of the program to have any other such type present. - use
if not isinstance(x, MyType): raise TypeError(...)to downcast when it is anticipated/expected that an inappropriate type might be given. - use
cast(MyType, val)to downcast sparingly, as this check is a no-op at runtime. - Do not annotate the return type of init unless you have to
-
How to write docstrings
- Always triple quotes
- One-line summary, with a period.
- Blank line, followed by more elaborate prose if necessary.
-
:param x: full sentence.,:returns: such-and-such.,:raises ExceptionType: when such-and-such occurs. - Do not repeat types in the docstring (Allow the function signature to handle this.)
- reference functions and classes in
backticks. reference parameter names inquotes. - Always use :param:? Sometimes? When is it okay to omit?
- Guess: If your docstring is one-line, it's okay to omit the field lists.
-
Import styling
- Use isort.
- Sort based on FQ module name, regardless of import form (from X, import X)
- Sort imported names alphabetically
- Use one imported name per line when a line exceeds 72 characters or 3 imported names
- Use a trailing comma for such imports
- Group stdlib imports first, followed by a blank line, then third party imports followed by a blank line, then package-local imports, followed by a blank line.
Edited by John Snow