Add is_dataclass().
This commit is contained in:
parent
3371af975f
commit
ab1a60f08c
31
pep-0557.rst
31
pep-0557.rst
|
@ -623,6 +623,16 @@ Module level helper functions
|
||||||
``replace()`` (or similarly named) method which handles instance
|
``replace()`` (or similarly named) method which handles instance
|
||||||
copying.
|
copying.
|
||||||
|
|
||||||
|
- ``is_dataclass(class_or_instance)``: Returns True if its parameter
|
||||||
|
is a dataclass or an instance of one, otherwise returns False.
|
||||||
|
|
||||||
|
If you need to know if a class is an instance of a dataclass (and
|
||||||
|
not a dataclass itself), then add a further check for ``not
|
||||||
|
isinstance(obj, type)``:
|
||||||
|
|
||||||
|
def is_dataclass_instance(obj):
|
||||||
|
return is_dataclass(obj) and not isinstance(obj, type)
|
||||||
|
|
||||||
.. _discussion:
|
.. _discussion:
|
||||||
|
|
||||||
Discussion
|
Discussion
|
||||||
|
@ -816,27 +826,6 @@ decision is to disallow the 3 known built-in mutable types: list,
|
||||||
dict, and set. For a complete discussion of this and other options,
|
dict, and set. For a complete discussion of this and other options,
|
||||||
see [#]_.
|
see [#]_.
|
||||||
|
|
||||||
Providing isdataclass()
|
|
||||||
-----------------------
|
|
||||||
|
|
||||||
An earlier version of this PEP defined an ``isdataclass(obj)`` helper
|
|
||||||
function. However, there was no known use case for this, and there
|
|
||||||
was debate on whether it should return ``True`` for instances or
|
|
||||||
classes or both. In the end, ``isdataclass()`` was removed.
|
|
||||||
|
|
||||||
The supported way of writing a function that checks if an object is a
|
|
||||||
dataclass instance or class is::
|
|
||||||
|
|
||||||
def isdataclass(obj):
|
|
||||||
try:
|
|
||||||
dataclasses.fields(obj)
|
|
||||||
return True
|
|
||||||
except TypeError:
|
|
||||||
return False
|
|
||||||
|
|
||||||
If needed, a further check for ``isinstance(obj, type)`` can be added
|
|
||||||
to discern if ``obj`` is a class.
|
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
========
|
========
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue