Skip to content

Commit 8961fbd

Browse files
committed
fix(typing): workaround for invalid ClassVar type on python 3.10
1 parent 16ffcf8 commit 8961fbd

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

koerce/annots.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -755,7 +755,7 @@ def __new__(
755755
else:
756756
self_qualname = f"{module}.{qualname}"
757757

758-
# TODO(kszucs): pass dct as localns to evaluate_annotations
758+
# TODO(kszucs): pass dct as localns to get_type_hints
759759
typehints = get_type_hints(annotations, module=module)
760760
for name, typehint in typehints.items():
761761
if get_type_origin(typehint) is ClassVar:

koerce/utils.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import sys
55
import typing
66
from collections.abc import Hashable
7-
from typing import Any, Optional, TypeVar
7+
from typing import Any, ClassVar, ForwardRef, Optional, TypeVar
88

99
from typing_extensions import Self
1010

@@ -15,6 +15,7 @@
1515

1616
get_type_args = typing.get_args
1717
get_type_origin = typing.get_origin
18+
_get_type_hints = typing.get_type_hints
1819

1920

2021
class 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
8993
def get_type_params(typ: Any) -> dict[TypeVar, type]:
9094
"""Get type parameters for a generic class.
9195

0 commit comments

Comments
 (0)