Zac-HD/shed

Refactor type hints for Python 3.10+

Zac-HD opened this issue ยท 7 comments

"""
# We want to get to this, but it takes some manual editing...

def f(
    value: Literal["Option1", "Option2", "Option3", "Option4", "Option5"] | None = None,
):
    pass
"""

from typing import Literal, Optional


def f(
    # The `value` argument is poorly upgraded to the Python 3.10 syntax
    value: Optional[
        Literal["Option1", "Option2", "Option3", "Option4", "Option5"]
    ] = None,
):
    pass


## need to nicely reformat arguments like 
helpful_file: None | (
        str
    ) = "some very long string aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
# because they show up all the time when upgrading from Optional[str] =

I think this output comes from pyupgrade and fixing it there is probably infeasible, but we could add custom LibCST logic to fix them after the fact.

Hi @Zac-HD could you explain this a bit more? Is it the support for None (instead of Optional) in typing?

Yep, but specifically that when upgrading to https://peps.python.org/pep-0604/ Optional[T] -> None | (\n T \n) is really ugly, and the "put the | None last" refactor method doesn't seem to work in these cases.

So we want to make sure that | None comes last in these cases. Got it :-)

Funny enough in the pyupgrade repo they did put None last in the example: https://github.com/asottile/pyupgrade#pep-604-typing-rewrites

@Zac-HD I cannot reproduce the example above... None always comes last as we had this done before: #39

Here is what I get when running shed try.py --refactor --py310-plus

helpful_file: (
    str
) | None = "some very long string aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

And

from typing import Literal


def f(
    # The `value` argument is poorly upgraded to the Python 3.10 syntax
    value: (Literal["Option1", "Option2", "Option3", "Option4", "Option5"])
    | None = None,
):
    pass

Huh, seems like this has been resolved upstream then ๐Ÿ™‚

On to another issue?