summaryrefslogtreecommitdiff
path: root/Lib
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2019-08-19 22:59:21 -0700
committerGitHub <noreply@github.com>2019-08-19 22:59:21 -0700
commit1271ee8187df31debda7c556882a51ec356ca534 (patch)
treebb0830d8e0d28a28b01d5f77ea8a0647669a5388 /Lib
parent9aa0ab1a97a9287420bef99803872879eaa45f8f (diff)
downloadcpython-git-1271ee8187df31debda7c556882a51ec356ca534.tar.gz
bpo-37868: Improve is_dataclass for instances. (GH-15325)
(cherry picked from commit b0f4dab8735f692bcfedcf0fa9a25e238a554bab) Co-authored-by: Eric V. Smith <ericvsmith@users.noreply.github.com>
Diffstat (limited to 'Lib')
-rw-r--r--Lib/dataclasses.py5
-rwxr-xr-xLib/test/test_dataclasses.py26
2 files changed, 29 insertions, 2 deletions
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index 23712fa870..2f0e5ff0b6 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -1015,13 +1015,14 @@ def fields(class_or_instance):
def _is_dataclass_instance(obj):
"""Returns True if obj is an instance of a dataclass."""
- return not isinstance(obj, type) and hasattr(obj, _FIELDS)
+ return hasattr(type(obj), _FIELDS)
def is_dataclass(obj):
"""Returns True if obj is a dataclass or an instance of a
dataclass."""
- return hasattr(obj, _FIELDS)
+ cls = obj if isinstance(obj, type) else type(obj)
+ return hasattr(cls, _FIELDS)
def asdict(obj, *, dict_factory=dict):
diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py
index facf9d2e2c..0885c9798f 100755
--- a/Lib/test/test_dataclasses.py
+++ b/Lib/test/test_dataclasses.py
@@ -1300,6 +1300,32 @@ class TestCase(unittest.TestCase):
self.assertTrue(is_dataclass(d.d))
self.assertFalse(is_dataclass(d.e))
+ def test_is_dataclass_when_getattr_always_returns(self):
+ # See bpo-37868.
+ class A:
+ def __getattr__(self, key):
+ return 0
+ self.assertFalse(is_dataclass(A))
+ a = A()
+
+ # Also test for an instance attribute.
+ class B:
+ pass
+ b = B()
+ b.__dataclass_fields__ = []
+
+ for obj in a, b:
+ with self.subTest(obj=obj):
+ self.assertFalse(is_dataclass(obj))
+
+ # Indirect tests for _is_dataclass_instance().
+ with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
+ asdict(obj)
+ with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
+ astuple(obj)
+ with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
+ replace(obj, x=0)
+
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.