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

℡╲_俬逩灬. 提交于 2020-01-03 08:46:07

问题


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):
            #...

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?

来源:https://stackoverflow.com/questions/53589794/pythonic-way-to-check-if-a-dataclass-field-has-a-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!