From ab1a60f08c8005ac5de6cd325b9b27dfeb1ecdee Mon Sep 17 00:00:00 2001 From: "Eric V. Smith" Date: Sat, 6 Jan 2018 11:10:27 -0500 Subject: [PATCH] Add is_dataclass(). --- pep-0557.rst | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/pep-0557.rst b/pep-0557.rst index 43563a0a9..a5c2e117e 100644 --- a/pep-0557.rst +++ b/pep-0557.rst @@ -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 ========