Skip to main content

Replace `Optional[T]` by `Union[T, None]`! 🎉

Project description

no-optional

Package version

This codemod replaces typing.Optional[T] by typing.Union[T, None] in the codebase.

Why?

This tool was inspired by a tweet from Sebastián Ramírez (as you see below), and a conversation between us.

image

As the tweet says, we have two reasons for doing this:

  1. It's more explicit to write Union[str, None] than Optional[str]. Mainly because Optional[str] doesn't mean that the attribute is optional. It only means that it accepts None as a possible value.
  2. On Python 3.10+ you can type annotate as str | None instead of the above two. Which is more similar to Union[str, None] than Optional[str].

Installation

pip install no-optional

Usage

Run the following on the repository you want to format:

python -m libcst.tool initialize .

Then, add the no_optional module to the modules list on the .libcst.codemod.yaml generated.

Then you are able to run:

python -m libcst.tool codemod main.NoOptionalCommand -j 1 <files>

License

This project is licensed under the terms of the MIT license.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page