I'm writing a routine that iterates all the fields in a dataclass. For each field that has a value it's added to a separate list.
The problem I have is that one of the fields is an enum. I can assert its datatype as an enum, but I can't access the usual .name and .value properties. Is it possible to cast the field to get access to the properties I'm after?
fields =[field, value) for field, vlaue in vars(temp_dto).items() if not field.startswith('__']
params_dict = {}
for name, value in fields:
if value != None:
params_dict.update({name : value})
if issubclass(type(value),enum.Enum):
print(value)
>> status.OPEN
Dataclass
class status(Enum):
OPEN = 1
CLOSED = 2
RESTRICTED = 3
@dataclass
class AccountDto:
account_id: int
name: str
region: str
status: status
CodePudding user response:
Just an addon, for dynamically typed things your IDE can have a problem with guessing types, but typing library comes with a cast
from enum import Enum
from typing import cast
class E(Enum):
a = "A"
class F:
pass
def create(s: str):
if s == "e":
return E("A")
if s == "f":
return F
x = create("e")
print(x.name) # mypy shows Cannot access member "name" for type "Type[F]"
x = cast(E, x)
print(x.name) # it works!
CodePudding user response:
Non issue, was caused by error with intellisense.