简体   繁体   中英

Check if a type is Union type in Python

I have defined a dataclass:

import dataclasses

@dataclasses.dataclass
class MyClass:
    attr1: int | None
    attr2: str | None

I can loop through the types of my attributes with:

for field in dataclasses.fields(MyClass):
    fieldname = field.name
    fieldtype = field.type 

But how can I check if type 'str' is in 'fieldtype' or get the list of types inside the union type?

You can use __args__ attribute of union type.

>>> import dataclasses
>>> import types
>>> 
>>> @dataclasses.dataclass
... class MyClass:
...     attr1: int | None
...     attr2: str | None
... 
>>> for field in dataclasses.fields(MyClass):
...     fieldname = field.name
...     fieldtype = field.type 
...     has_str_exists = False
...     if isinstance(fieldtype, types.UnionType):
...         fieldtype = fieldtype.__args__
...         has_str_exists = str in fieldtype
...     print(f"{fieldname=} {fieldtype=} {has_str_exists=}")
... 
fieldname='attr1' fieldtype=(<class 'int'>, <class 'NoneType'>) has_str_exists=False
fieldname='attr2' fieldtype=(<class 'str'>, <class 'NoneType'>) has_str_exists=True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM