Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.10] bpo-45663: Fix is_dataclass() for dataclasses which are subclasses of types.GenericAlias (GH-29294) #29925

Merged
merged 1 commit into from
Dec 5, 2021
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
2 changes: 1 addition & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1211,7 +1211,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 @@ -8,6 +8,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 @@ -1350,6 +1351,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`.