asottile / pyupgrade

A tool (and pre-commit hook) to automatically upgrade syntax for newer versions of the language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypedDict with Generics are not reformatted correctly

j00bar opened this issue · comments

If I have:

from typing import TypedDict
from typing import TypeVar

T = TypeVar("T")

GenericEnvelope = TypedDict("GenericEnvelope", {"editable_fields": T, "readonly_fields": T}, total=False)

... when pyupgrade runs across it, it will convert it to:

class GenericEnvelope(TypedDict, total=False):
    editable_fields: T
    readonly_fields: T

This is incorrect - as T cannot be referenced like this unless GenericEnvelope also inherits from typing.Generic[T]. Complicating things further, a class subclassing from TypedDict and Generic is only supported of Python 3.11.

Perhaps there's a better way, but it would seem that for version of Python before 3.11, it should be left as a call to the TypedDict function if the attributes are generics; and for Python 3.11 and greater, Generic[T] needs to be added as an additional superclass.

Thanks so much!

pyupgrade can't really know that the values are generics so there isn't much that can be done here. you can work around this by aliasing TypedDict