(Original question title: Is it “mandatory” to use spaces around the |
in Python type annotations?)
The “Union operator” |
does not appear in the list of operators to alway surround by spaces in PEP8’s other recommendations. Hence, it should be OK to style it similar to arithmetic operators and drop the spaces inside parentheses, brackets, or if the operator has higher priority than other operators in the expression.
In my view, dropping the spaces improves readability in the follwing examples because it is easier to recognize the structure of the expressions:
Argument list:
- def __init__(self, *args: str | None, **kwargs: Any):
+ def __init__(self, *args: str|None, **kwargs: Any):
Variable with default value:
- level: str | int = 'warn'
+ level: str|int = 'warn'
Inside brackets:
- tuple[str | None, str | None, Sequence[int]]
+ tuple[str|None, str|None, Sequence[int]]
Complex construct:
- def __init__(self, defaults: dict[str | binary, Any] | None = None):
+ def __init__(self, defaults: dict[str|binary, Any] | None = None):
OTOH, all examples I found in type-annotation guides use spaces around |
. The “black” formatter forces them.
“flake8” and “ruff” can be configured to ignore E227 (“missing whitespace around bitwise or shift operator”).
Are there other reasons for always using spaces than “this is what black
does” or “this is what the PEP examples use”?
7