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
Per the documentation:
To define a union, use e.g.
Union[int, str]or the shorthandint | 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.