Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/Kludex/no-optional
Replace `Optional[T]` by `Union[T, None]` 👀
https://github.com/Kludex/no-optional
Last synced: 26 days ago
JSON representation
Replace `Optional[T]` by `Union[T, None]` 👀
- Host: GitHub
- URL: https://github.com/Kludex/no-optional
- Owner: Kludex
- License: mit
- Created: 2022-06-14T04:53:33.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2022-06-25T06:38:39.000Z (over 2 years ago)
- Last Synced: 2024-11-16T07:26:44.160Z (27 days ago)
- Language: Python
- Homepage:
- Size: 24.4 KB
- Stars: 55
- Watchers: 3
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-python-code-formatters - no-optional
README
no-optional
This [codemod](https://libcst.readthedocs.io/en/stable/codemods_tutorial.html) 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](https://twitter.com/tiangolo) (as you see below), and a conversation between us.
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`](https://github.com/asottile/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`](https://peps.python.org/pep-0563/) for versions below Python 3.10.
## Installation
```bash
pip install no-optional
```## Usage
Run the following on the repository you want to format:
```bash
python -m no_optional
```You can also use the pre-commit. Add the following to your `.pre-commit-config.yaml` file:
```yaml
- 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.