This codemod replaces typing.Optional[T]
by typing.Union[T, None]
in the codebase.
This tool was inspired by a tweet from Sebastián RamÃrez (as you see below), and a conversation between us.
As the tweet says, we have two reasons for doing this:
- It's more explicit to write
Union[str, None]
thanOptional[str]
. Mainly becauseOptional[str]
doesn't mean that the attribute is optional. It only means that it acceptsNone
as a possible value. - On Python 3.10+ you can type annotate as
str | None
instead of the above two. Which is more similar toUnion[str, None]
thanOptional[str]
.
pyupgrade
is great but no-optional
is better when you need runtime support like for FastAPI
and pydantic
.
The reason being that no-optional
just does the replacement. On the other hand, pyupgrade
requires from __future__ import annotations
for versions below Python 3.10.
pip install no-optional
Run the following on the repository you want to format:
python -m no_optional <files>
You can also use the pre-commit. Add the following to your .pre-commit-config.yaml
file:
- repo: https://github.com/Kludex/no-optional
rev: 0.4.0
hooks:
- id: no_optional
This project is licensed under the terms of the MIT license.