Python type hints have evolved remarkably across versions, for example from Union[str, List[str]] to str | list[str]. (I know that both are valid, but I (and the team) find the newer more readable.) Is there a tool to migrate an entire codebase?

3 Replies 3

Per the documentation:

To define a union, use e.g. Union[int, str] or the shorthand int | str. Using that shorthand is recommended.

So, as with many new language features, the old syntax remains valid and there is seemingly no move to deprecate direct usage of Union. PyCharm at the very least does not seem to provide inspections for PEP 604, which is unfortunate since my general recommendation for performing mass syntax migrations is to follow IDE inspections.

Personally I would simply perform a RegExp replace (CTRL+SHIFT+R) if this is important, for example replacing the pattern Union\[([^,]+),\s?([^\]]+)\] with $1 | $2.

There is a fixable ruff rule UP007, and pyupgrade also has a similar one.

ruff check src --fix --select UP007

should do the trick, and enabling this rule in your config will prevent accidentally reintroducing Unions.

Ruff's fixable UP006 can sometimes convert deprecated typing.List[T] aliases and the like to their list[T] equivalents. The rule is enabled by default on 3.9+; fixing needs to be enabled manually.

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.