hauntsaninja / no_implicit_optional

A codemod to make your implicit optional type hints PEP 484 compliant.
MIT License
79 stars 8 forks source link

Offer option to transform implicit optionals to `T | None` #7

Closed daneah closed 1 year ago

daneah commented 1 year ago

This has been a huge time saver, thanks for your work.

I'm a fan of the T | None syntax especially in a shop where we're using Python and TypeScript because the code is more concise and similar between languages (with TypeScript using e.g. T | undefined or T | null). It would be lovely to be able to leverage this tool to use the T | None syntax over the Optional import + wrapper if explicitly requested.

If there are good reasons not to do this, I'd be interested and understanding!

hauntsaninja commented 1 year ago

Thanks!

The main reason I hadn't yet added support for T | None is because the syntax is only fully supported on Python 3.10 and newer. On older Pythons, static type checkers are fine with it if you use from __future__ import annotations, but runtime uses of types will break (see e.g. https://mypy.readthedocs.io/en/stable/runtime_troubles.html).

Anyway, I'll definitely add a flag for it. In the meantime, converting Optional[T] to T | None is one of the things pyupgrade can do: https://github.com/asottile/pyupgrade#pep-604-typing-rewrites

daneah commented 1 year ago

Oh, I didn't even think about piping this through pyupgrade afterward. Since that's another favorite of mine, that's very doable. Cheers!

hauntsaninja commented 1 year ago

Thanks, released in 1.3