Skip to content

Commit

Permalink
Fix Dataclass typehint for mypy 0.990+ (fixes #64)
Browse files Browse the repository at this point in the history
  • Loading branch information
oxan committed Nov 10, 2022
1 parent ef3aa4b commit 27cd263
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions rest_framework_dataclasses/types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Some type definitions that can be useful.

from typing import Dict
from typing import ClassVar, Dict, Union

try:
# Python 3.8 and later
Expand All @@ -9,6 +9,14 @@
from typing_extensions import Final, Literal, Protocol


# Note that this doesn't actually work yet (https://stackoverflow.com/a/55240861)
class Dataclass(Protocol):
__dataclass_fields__: Dict
# As dataclasses don't have a baseclass, we typehint them using a protocol matching the injected `__dataclass_fields__`
# attribute. Mypy 0.990 changed the attribute from an instance variable to a ClassVar, so use an union for compatibility
# with both older and newer versions. For reference, see https://stackoverflow.com/a/55240861 and
# https://github.com/python/mypy/issues/14029.
class NewStyleDataclassProtocol(Protocol):
__dataclass_fields__: ClassVar[dict]

class OldStyleDataclassProtocol(Protocol):
__dataclass_fields__: dict

Dataclass = Union[OldStyleDataclassProtocol, NewStyleDataclassProtocol]

0 comments on commit 27cd263

Please sign in to comment.