Check if a field is typing.Optional

前端 未结 5 625
死守一世寂寞
死守一世寂寞 2021-01-18 05:44

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

Example code:

from typing import Optional
import re
from dataclasses import         


        
5条回答
  •  时光说笑
    2021-01-18 06:06

    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)))
    

提交回复
热议问题