Pythonic way to check if a dataclass field has a default value

add*_*990 7 python python-3.x python-dataclasses

I've been using python 3.7 lately and was looking for ways to leverage the new dataclasses. Basically I had a method that iterates over the dataclass fields and checks if they have a default value:

from dataclasses import fields, MISSING

@classmethod
def from_json(cls)
    datacls_fields = fields(cls)
    for field in datacls_fields:
        if  (field.default != MISSING):
            #...
Run Code Online (Sandbox Code Playgroud)

However in the official documentation, it says:

MISSING value is a sentinel object used to detect if the default and default_factory parameters are provided. This sentinel is used because None is a valid value for default. No code should directly use the MISSING value.

Anyone knows a better/more pythonic way to do it?

Cha*_*thk 8

MISSING这是python 源代码中的定义dataclasses.py

# A sentinel object to detect if a parameter is supplied or not.  Use
# a class to give it a better repr.
class _MISSING_TYPE:
    pass
MISSING = _MISSING_TYPE()
Run Code Online (Sandbox Code Playgroud)

定义非常清楚,它的用例只是检查是否已提供参数,并区分 的值None和未提供的值:

def my_func(a=MISSING):
    if a is not MISSING:
        # a value has been supplied, whatever his value
Run Code Online (Sandbox Code Playgroud)

所以在代码中使用它来进行值比较是完全可以的。通过告诉“No code should direct use the MISSING value”,他们只是警告我们该变量没有特定用途(除了用于比较),并且不应在代码中使用以避免意外行为。

您应该更新代码以使用更Pythonic 的语法is not MISSING

from dataclasses import fields, MISSING

@classmethod
def from_json(cls)
    datacls_fields = fields(cls)
    for field in datacls_fields:
        if field.default is not MISSING:

Run Code Online (Sandbox Code Playgroud)