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
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 Optional
er. 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']