Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
bpo-45663: Fix is_dataclass() for dataclasses which are subclasses of…
… types.GenericAlias (GH-29294)

(cherry picked from commit 446be16)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
  • Loading branch information
serhiy-storchaka authored and miss-islington committed Dec 5, 2021
commit c6ef4d8bf07ca4add65eccfbe774ed0018c6fd12
2 changes: 1 addition & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,7 @@ def _is_dataclass_instance(obj):
def is_dataclass(obj):
"""Returns True if obj is a dataclass or an instance of a
dataclass."""
cls = obj if isinstance(obj, type) else type(obj)
cls = obj if isinstance(obj, type) and not isinstance(obj, GenericAlias) else type(obj)
return hasattr(cls, _FIELDS)


Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import pickle
import inspect
import builtins
import types
import unittest
from unittest.mock import Mock
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol
Expand Down Expand Up @@ -1348,6 +1349,17 @@ class B:
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
replace(obj, x=0)

def test_is_dataclass_genericalias(self):
@dataclass
class A(types.GenericAlias):
origin: type
args: type
self.assertTrue(is_dataclass(A))
a = A(list, int)
self.assertTrue(is_dataclass(type(a)))
self.assertTrue(is_dataclass(a))


def test_helper_fields_with_class_instance(self):
# Check that we can call fields() on either a class or instance,
# and get back the same thing.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`dataclasses.is_dataclass` for dataclasses which are subclasses of
:class:`types.GenericAlias`.