pythonmypyflake8python-black

Automatically modernize python syntax


I'm looking for a tool that will automatically modernize my python code. Something that will take a python version as configuration, and automatically modernize the code for that version.

For example, with python 3.9+ we can convert all

from typing import List

my_list:List[str] = []

to

my_list:list[str] = []

And with python 3.10+ we can convert all

from typing import Optional

my_optional: Optional[str] = None

to

my_optional: str | None = None

I'm sure there are other syntax updates that can also be done.

Is there some tool that does this? I've looked into mypy, black, and flake8 and I can't see anything that will convert automatically for me, or even warn me about these so that I can update them manually.


Solution

  • pyupgrade with the --py311-plus option seems to do what I want.

    It seems to leave in the unused imports, but using autoflake I can correct them.

    Another option is ruff which does EXACTLY what I want.