Skip to content

Commit 8738a1d

Browse files
authored
fix: DataclassInstance and AttrInstance protocols (#108)
* refactor: rename DataclassesProtocol -> DataclassInstance * fix: instance protocol classvars * fix: 3.8 hint * chore: black
1 parent f23a4ea commit 8738a1d

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

fgpyo/util/inspect.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import types as python_types
33
import typing
44
from typing import Any
5+
from typing import ClassVar
56
from typing import Dict
67
from typing import FrozenSet
78
from typing import Iterable
@@ -68,19 +69,20 @@ def get_attr_fields_dict(cls: type) -> Dict[str, dataclasses.Field]: # type: ig
6869
MISSING = frozenset({DATACLASSES_MISSING})
6970

7071
if TYPE_CHECKING: # pragma: no cover
71-
from _typeshed import DataclassInstance as DataclassesProtocol
72+
from _typeshed import DataclassInstance
7273
else:
73-
74-
class DataclassesProtocol(Protocol):
75-
__dataclasses_fields__: Dict[str, dataclasses.Field]
74+
# https://github.com/python/typeshed/blob/727f3c4320d2af3af2f16695e24dd78e79b7c070/stdlib/_typeshed/__init__.pyi#L348
75+
# TODO: update the hint to `Field[Any]` when we drop support for 3.8
76+
class DataclassInstance(Protocol):
77+
__dataclasses_fields__: ClassVar[Dict[str, dataclasses.Field]]
7678

7779

7880
if TYPE_CHECKING and _use_attr: # pragma: no cover
7981
from attr import AttrsInstance
8082
else:
81-
83+
# https://github.com/python-attrs/attrs/blob/f7f317ae4c3790f23ae027db626593d50e8a4e88/src/attr/_typing_compat.pyi#L9
8284
class AttrsInstance(Protocol): # type: ignore[no-redef]
83-
__attrs_attrs__: Dict[str, Any]
85+
__attrs_attrs__: ClassVar[Any]
8486

8587

8688
def is_attr_class(cls: type) -> bool: # type: ignore[arg-type]
@@ -90,7 +92,7 @@ def is_attr_class(cls: type) -> bool: # type: ignore[arg-type]
9092

9193
_MISSING_OR_NONE: FrozenSet[Any] = frozenset({*MISSING, None})
9294
"""Set of values that are considered missing or None for dataclasses or attr classes"""
93-
_DataclassesOrAttrClass: TypeAlias = Union[DataclassesProtocol, AttrsInstance]
95+
_DataclassesOrAttrClass: TypeAlias = Union[DataclassInstance, AttrsInstance]
9496
"""
9597
TypeAlias for dataclasses or attr classes. Mostly nonsense because they are not true types, they
9698
are traits, but there is no python trait-tester.
@@ -103,7 +105,7 @@ def is_attr_class(cls: type) -> bool: # type: ignore[arg-type]
103105

104106

105107
def _get_dataclasses_fields_dict(
106-
class_or_instance: Union[DataclassesProtocol, Type[DataclassesProtocol]],
108+
class_or_instance: Union[DataclassInstance, Type[DataclassInstance]],
107109
) -> Dict[str, dataclasses.Field]:
108110
"""Get a dict from field name to Field for a dataclass class or instance."""
109111
return {field.name: field for field in get_dataclasses_fields(class_or_instance)}

0 commit comments

Comments
 (0)