检查字段是否正在输入

检查字段是否正在输入

本文介绍了检查字段是否正在输入.可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查类中的字段是否正在键入的最佳方法是什么.可选?

What is the best way to check if a field from a class is typing.Optional?

示例代码:

from typing import Optional
import re
from dataclasses import dataclass, fields

@dataclass(frozen=True)
class TestClass:
    required_field_1: str
    required_field_2: int
    optional_field: Optional[str]

def get_all_optional_fields(fields) -> list:
    return [field.name for field in fields if __is_optional_field(field)]

def __is_optional_field(field) -> bool:
    regex = '^typing.Union\[.*, NoneType\]$'
    return re.match(regex, str(field.type)) is not None

print(get_all_optional_fields(fields(TestClass)))

其中fields 来自dataclasses,我想列出所有Optional 字段.我现在正在做的解决这个问题是使用基于字段名称的正则表达式,但我不喜欢这种方法.有没有更好的方法?

Where fields is from dataclasses, I wanna list all the Optional fields.What I'm doing at this moment to solve it, is using a Regex-based on the field name, but I don't like this approach. Is there a better way of doing it?

推荐答案

Optional[X] 等价于 Union[X, None].所以你可以这样做,

Optional[X] is equivalent to Union[X, None]. So you could do,

import re
from typing import Optional

from dataclasses import dataclass, fields


@dataclass(frozen=True)
class TestClass:
    required_field_1: str
    required_field_2: int
    optional_field: Optional[str]


def get_optional_fields(klass):
    class_fields = fields(klass)
    for field in class_fields:
        if (
            hasattr(field.type, "__args__")
            and len(field.type.__args__) == 2
            and field.type.__args__[-1] is type(None)
        ):
            # Check if exactly two arguments exists and one of them are None type
            yield field.name


print(list(get_optional_fields(TestClass)))

这篇关于检查字段是否正在输入.可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 23:22