Add is_dataclass().

This commit is contained in:
Eric V. Smith 2018-01-06 11:10:27 -05:00
parent 3371af975f
commit ab1a60f08c
1 changed files with 10 additions and 21 deletions

View File

@ -623,6 +623,16 @@ Module level helper functions
``replace()`` (or similarly named) method which handles instance
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
@ -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,
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
========