Skip to content

Commit b0f4dab

Browse files
authored
bpo-37868: Improve is_dataclass for instances. (GH-15325)
1 parent d3c8d73 commit b0f4dab

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

Lib/dataclasses.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,13 +1015,14 @@ def fields(class_or_instance):
10151015

10161016
def _is_dataclass_instance(obj):
10171017
"""Returns True if obj is an instance of a dataclass."""
1018-
return not isinstance(obj, type) and hasattr(obj, _FIELDS)
1018+
return hasattr(type(obj), _FIELDS)
10191019

10201020

10211021
def is_dataclass(obj):
10221022
"""Returns True if obj is a dataclass or an instance of a
10231023
dataclass."""
1024-
return hasattr(obj, _FIELDS)
1024+
cls = obj if isinstance(obj, type) else type(obj)
1025+
return hasattr(cls, _FIELDS)
10251026

10261027

10271028
def asdict(obj, *, dict_factory=dict):

Lib/test/test_dataclasses.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1300,6 +1300,32 @@ class D:
13001300
self.assertTrue(is_dataclass(d.d))
13011301
self.assertFalse(is_dataclass(d.e))
13021302

1303+
def test_is_dataclass_when_getattr_always_returns(self):
1304+
# See bpo-37868.
1305+
class A:
1306+
def __getattr__(self, key):
1307+
return 0
1308+
self.assertFalse(is_dataclass(A))
1309+
a = A()
1310+
1311+
# Also test for an instance attribute.
1312+
class B:
1313+
pass
1314+
b = B()
1315+
b.__dataclass_fields__ = []
1316+
1317+
for obj in a, b:
1318+
with self.subTest(obj=obj):
1319+
self.assertFalse(is_dataclass(obj))
1320+
1321+
# Indirect tests for _is_dataclass_instance().
1322+
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1323+
asdict(obj)
1324+
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1325+
astuple(obj)
1326+
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1327+
replace(obj, x=0)
1328+
13031329
def test_helper_fields_with_class_instance(self):
13041330
# Check that we can call fields() on either a class or instance,
13051331
# and get back the same thing.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix dataclasses.is_dataclass when given an instance that never raises
2+
AttributeError in __getattr__. That is, an object that returns something
3+
for __dataclass_fields__ even if it's not a dataclass.

0 commit comments

Comments
 (0)