This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author GBeauregard
Recipients GBeauregard, JelleZijlstra, gvanrossum, kj
Date 2022-01-26.20:30:38
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1643229038.65.0.790137341824.issue46539@roundup.psfhosted.org>
In-reply-to
Content
Consider the following code on 3.11 main:

```
from typing import Annotated, ClassVar, get_type_hints

class DC:
    a: ClassVar[int] = 3
    b: ClassVar["int"] = 3
    c: "ClassVar[int]" = 3
    d: Annotated[ClassVar[int], (2, 5)] = 3
    e: Annotated[ClassVar["int"], (2, 5)] = 3
    f: "Annotated[ClassVar[int], (2, 5)]" = 3

class DC_Special_ForwardRef:
    g: Annotated["ClassVar[int]", (] = 3

# OK
assert get_type_hints(DC, globals(), locals()) == {
    "a": ClassVar[int],
    "b": ClassVar[int],
    "c": ClassVar[int],
    "d": ClassVar[int],
    "e": ClassVar[int],
    "f": ClassVar[int],
}

# TypeError: typing.ClassVar[int] is not valid as type argument
get_type_hints(DC_Special_ForwardRef, globals(), locals())
```

Currently, the `Annotated["ClassVar[int]", (2, 5)]` annotation raises at runtime when `get_type_hints` is called, but all the other forward reference annotations are okay.

My understanding is this is because when typing._type_check runs on a type where special forms are allowed it's possible for the typing._type_convert it calls it itself run a typing._type_check on contained forward references. However, if that forward reference was itself a special form then it's possible to get an error because typing._type_check doesn't pass on that special forms are allowed.

I have drafted a patch to pass on this information. This will become important in the future as more special forms are allowed to wrap each other, such as allowing Final and ClassVar to nest each other in dataclasses, or when Required and NotRequired land. In the future we may also want to reconsider runtime restrictions on special forms in `typing.py` entirely and instead choose to leave this to type checkers.

Is my analysis/patch approach okay? Forward references can be tricky. Should we be discussing runtime restrictions in typing.py more generally in the future?
History
Date User Action Args
2022-01-26 20:30:38GBeauregardsetrecipients: + GBeauregard, gvanrossum, JelleZijlstra, kj
2022-01-26 20:30:38GBeauregardsetmessageid: <1643229038.65.0.790137341824.issue46539@roundup.psfhosted.org>
2022-01-26 20:30:38GBeauregardlinkissue46539 messages
2022-01-26 20:30:38GBeauregardcreate