python 打字的类型是什么。可选

Kev*_*ang 5 python python-3.x

我想使用打字get_type_hints方法来获取参数注释。但是我在Python3.6.8 中遇到了这个问题

a = typing.Optional[int]
type(a)
Out[13]: typing.Union
type(a) == typing.Union
Out[14]: False
type(a) == type(typing.Optional)
Out[23]: False
type(a) == type(typing.Optional[int])
Out[24]: True
repr(type(a))
Out[25]: 'typing.Union'
repr(typing.Union)
Out[26]: 'typing.Union'
Run Code Online (Sandbox Code Playgroud)

typing.Optional除了比较repr不是很pythonic的类型之外,似乎没有通用的方法来判断一个类型是否是。有破解吗?

PS 在 3.7 有typing._GenericAlias,它工作得很好。

Tek*_*ill 5

我相信这在这篇文章中得到了回答Check if a field is typing.Optional

我也粘贴在下面:

Optional[X]相当于Union[X, None]。所以你可以这样做,

    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)))
Run Code Online (Sandbox Code Playgroud)