Skip to content

Commit 02c1457

Browse files
bpo-37868: Improve is_dataclass for instances. (GH-15325)
(cherry picked from commit b0f4dab) Co-authored-by: Eric V. Smith <[email protected]>
1 parent 0fcdd8d commit 02c1457

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
@@ -1011,13 +1011,14 @@ def fields(class_or_instance):
10111011

10121012
def _is_dataclass_instance(obj):
10131013
"""Returns True if obj is an instance of a dataclass."""
1014-
return not isinstance(obj, type) and hasattr(obj, _FIELDS)
1014+
return hasattr(type(obj), _FIELDS)
10151015

10161016

10171017
def is_dataclass(obj):
10181018
"""Returns True if obj is a dataclass or an instance of a
10191019
dataclass."""
1020-
return hasattr(obj, _FIELDS)
1020+
cls = obj if isinstance(obj, type) else type(obj)
1021+
return hasattr(cls, _FIELDS)
10211022

10221023

10231024
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
@@ -1294,6 +1294,32 @@ class D:
12941294
self.assertTrue(is_dataclass(d.d))
12951295
self.assertFalse(is_dataclass(d.e))
12961296

1297+
def test_is_dataclass_when_getattr_always_returns(self):
1298+
# See bpo-37868.
1299+
class A:
1300+
def __getattr__(self, key):
1301+
return 0
1302+
self.assertFalse(is_dataclass(A))
1303+
a = A()
1304+
1305+
# Also test for an instance attribute.
1306+
class B:
1307+
pass
1308+
b = B()
1309+
b.__dataclass_fields__ = []
1310+
1311+
for obj in a, b:
1312+
with self.subTest(obj=obj):
1313+
self.assertFalse(is_dataclass(obj))
1314+
1315+
# Indirect tests for _is_dataclass_instance().
1316+
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1317+
asdict(obj)
1318+
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1319+
astuple(obj)
1320+
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1321+
replace(obj, x=0)
1322+
12971323
def test_helper_fields_with_class_instance(self):
12981324
# Check that we can call fields() on either a class or instance,
12991325
# 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)