ruff icon indicating copy to clipboard operation
ruff copied to clipboard

UP: Rule for rewriting `typing_extensions.TypeAliasType` as `type ...` on Python 3.12

Open tmke8 opened this issue 1 year ago • 1 comments
trafficstars

On Python 3.12, the new type alias syntax, type X = Y, produces a typing.TypeAliasType object, which has been backported to typing_extensions.

And pydantic makes use of this typing_extensions.TypeAliasType: https://docs.pydantic.dev/latest/concepts/types/#named-type-aliases

From the pydantic docs:

from typing import List, TypeVar

from annotated_types import Gt
from typing_extensions import Annotated, TypeAliasType

T = TypeVar('T')  # or a `bound=SupportGt`

PositiveList = TypeAliasType(
    'PositiveList', List[Annotated[T, Gt(0)]], type_params=(T,)
)

(Why aren't they just using TypeAlias? Because then pydantic can't access the name of the alias. And there are also problems with recursive aliases.)

It would be nice if this could automatically be rewritten to

from annotated_types import Gt
from typing import Annotated

type PositiveList[T] = list[Annotated[T, Gt(0)]]

on Python 3.12.

This should be an entirely safe fix, because it's just different syntax to produce the same result.

tmke8 avatar May 14 '24 10:05 tmke8

Makes sense to me!

zanieb avatar May 14 '24 11:05 zanieb