Check if a field is typing.Optional

前端 未结 5 627
死守一世寂寞
死守一世寂寞 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:05

    Another approach (That works on both python 3.7 & and 3.8) is to relay on how the set Union operation works:

    union([x,y],[y])= union([x],[y]) = union(union([x],[y]),[x,y])

    The logic is that Optional type can't be Optionaler. While you can't directly know if a type is nullable/optional, Optional[type] would be the same as type is the type is optional and other (Union[type,None] to be exact) otherwise.

    So, in our case:

    Union[SomeType,None] == Union[Union[SomeType,None]]
    

    (the first is eqivalent to Optional[SomeType] and the second to Optional[Optional[SomeType]]

    This allows very easy check for Optional values:

    from dataclasses import dataclass, fields
    from typing import Optional
    
    
    @dataclass()
    class DC:
        x: Optional[str] = None
        y: str = "s"
    
    
    def get_optional_fields(cls):
        fields_list = fields(cls)
        return [
            field.name 
            for field in fields_list if 
            field.type == Optional[field.type]
        ]
    
    
    
    if __name__ == '__main__':
        print(get_optional_fields(DC())) # ['x']
    

提交回复
热议问题