1

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.

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
niltz
  • 1,014
  • 11
  • 28
  • 2
    For what it's worth, the second example you give is not obviously bad. `list[str]` is obviously better than `List[str]` in modern Python, but there are people who still prefer `Optional[str]` to `str | None`, and `Optional` is not deprecated, whereas `List` is. – Silvio Mayolo Apr 03 '23 at 15:15
  • The reason why something like this is missing is because as pointed out by Silvio, none of the above mentioned examples are depreciated and are ok to use, even if not best practice. With List for example, if removed, it would break a lot of applications which were created before Python 3.9 and rely on that specific package. I recommend doing some Find&Replacing which, depending on the size of your application could be fairly simple or not a viable option. – CaptainCsaba Apr 03 '23 at 15:20
  • This is for my own internal apps where I can ensure python 3.11 for all the things. – niltz Apr 03 '23 at 18:10
  • 1
    Questions asking for recommendations of tools, libraries, or other resources are explicitly off-topic here. As I understand it, it's because they used to attract lots of spam when they were allowed. – CrazyChucky Apr 20 '23 at 16:44

1 Answers1

1

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.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
niltz
  • 1,014
  • 11
  • 28