The Wayback Machine - https://web.archive.org/web/20230319195841/https://github.com/Kludex/no-optional
Skip to content

Kludex/no-optional

main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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].

Alternative

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.

Installation

pip install no-optional

Usage

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

License

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

About

Replace `Optional[T]` by `Union[T, None]` ๐Ÿ‘€

Resources

License

Stars

Watchers

Forks

Sponsor this project