44import sys
55import typing
66from collections .abc import Hashable
7- from typing import Any , Optional , TypeVar
7+ from typing import Any , ClassVar , ForwardRef , Optional , TypeVar
88
99from typing_extensions import Self
1010
1515
1616get_type_args = typing .get_args
1717get_type_origin = typing .get_origin
18+ _get_type_hints = typing .get_type_hints
1819
1920
2021class FakeType :
@@ -58,22 +59,26 @@ class properties.
5859 if isinstance (obj , dict ):
5960 if module is None :
6061 raise TypeError ("`module` must be provided to evaluate type hints" )
62+
63+ # turn string annotations into ForwardRef objects with the
64+ # is_class flag set, so ClassVar annotations won't raise
65+ # on Python 3.10
66+ obj = {
67+ k : ForwardRef (v , is_class = True ) if isinstance (v , str ) else v
68+ for k , v in obj .items ()
69+ }
6170 obj = FakeType (module = module , annotations = obj )
6271 mod = sys .modules .get (module , None )
6372 globalns = getattr (mod , "__dict__" , None )
6473
65- try :
66- hints = typing .get_type_hints (
67- obj , globalns = globalns , localns = localns , include_extras = include_extras
68- )
69- except TypeError :
70- return {}
71-
74+ hints = _get_type_hints (
75+ obj , globalns = globalns , localns = localns , include_extras = include_extras
76+ )
7277 if include_properties :
7378 for name in dir (obj ):
7479 attr = getattr (obj , name )
7580 if isinstance (attr , property ):
76- annots = typing . get_type_hints (
81+ annots = _get_type_hints (
7782 attr .fget ,
7883 globalns = globalns ,
7984 localns = localns ,
@@ -85,7 +90,6 @@ class properties.
8590 return hints
8691
8792
88- # TODO(kszucs): memoize this function
8993def get_type_params (typ : Any ) -> dict [TypeVar , type ]:
9094 """Get type parameters for a generic class.
9195
0 commit comments