bpo-32499: Add dataclasses.is_dataclass(obj), which returns True if o… · python/cpython@e7ba013 (original) (raw)
`@@ -16,6 +16,7 @@
`
16
16
`'astuple',
`
17
17
`'make_dataclass',
`
18
18
`'replace',
`
``
19
`+
'is_dataclass',
`
19
20
` ]
`
20
21
``
21
22
`# Raised when an attempt is made to modify a frozen class.
`
`@@ -615,11 +616,17 @@ def fields(class_or_instance):
`
615
616
`return tuple(f for f in fields.values() if f._field_type is _FIELD)
`
616
617
``
617
618
``
618
``
`-
def _isdataclass(obj):
`
``
619
`+
def _is_dataclass_instance(obj):
`
619
620
`"""Returns True if obj is an instance of a dataclass."""
`
620
621
`return not isinstance(obj, type) and hasattr(obj, _MARKER)
`
621
622
``
622
623
``
``
624
`+
def is_dataclass(obj):
`
``
625
`+
"""Returns True if obj is a dataclass or an instance of a
`
``
626
`+
dataclass."""
`
``
627
`+
return hasattr(obj, _MARKER)
`
``
628
+
``
629
+
623
630
`def asdict(obj, *, dict_factory=dict):
`
624
631
`"""Return the fields of a dataclass instance as a new dictionary mapping
`
625
632
` field names to field values.
`
`@@ -639,12 +646,12 @@ class C:
`
639
646
` dataclass instances. This will also look into built-in containers:
`
640
647
` tuples, lists, and dicts.
`
641
648
` """
`
642
``
`-
if not _isdataclass(obj):
`
``
649
`+
if not _is_dataclass_instance(obj):
`
643
650
`raise TypeError("asdict() should be called on dataclass instances")
`
644
651
`return _asdict_inner(obj, dict_factory)
`
645
652
``
646
653
`def _asdict_inner(obj, dict_factory):
`
647
``
`-
if _isdataclass(obj):
`
``
654
`+
if _is_dataclass_instance(obj):
`
648
655
`result = []
`
649
656
`for f in fields(obj):
`
650
657
`value = _asdict_inner(getattr(obj, f.name), dict_factory)
`
`@@ -678,12 +685,12 @@ class C:
`
678
685
` tuples, lists, and dicts.
`
679
686
` """
`
680
687
``
681
``
`-
if not _isdataclass(obj):
`
``
688
`+
if not _is_dataclass_instance(obj):
`
682
689
`raise TypeError("astuple() should be called on dataclass instances")
`
683
690
`return _astuple_inner(obj, tuple_factory)
`
684
691
``
685
692
`def _astuple_inner(obj, tuple_factory):
`
686
``
`-
if _isdataclass(obj):
`
``
693
`+
if _is_dataclass_instance(obj):
`
687
694
`result = []
`
688
695
`for f in fields(obj):
`
689
696
`value = _astuple_inner(getattr(obj, f.name), tuple_factory)
`
`@@ -751,7 +758,7 @@ class C:
`
751
758
`# We're going to mutate 'changes', but that's okay because it's a new
`
752
759
`# dict, even if called with 'replace(obj, **my_changes)'.
`
753
760
``
754
``
`-
if not _isdataclass(obj):
`
``
761
`+
if not _is_dataclass_instance(obj):
`
755
762
`raise TypeError("replace() should be called on dataclass instances")
`
756
763
``
757
764
`# It's an error to have init=False fields in 'changes'.
`