我有一个这样的数据类:
@dataclass
class Bla:
arg1: Optional[int] = None
arg2: Optional[str] = None
arg3: Optional[Dict[str, str]] = None
我想要这种行为:
>>> bla = Bla(arg1=None, arg2=None, arg3=None)
>>> asdict(bla)
{'arg1': None, 'arg2': None, 'arg3': None}
>>> bla = Bla()
{}
在这种特定情况下,我可以使用 a dict,但我会失去拥有类型提示的可能性(并使用 mypy)
所以我尝试了这个:
class none:
...
@dataclass
class Bla:
arg1: Union[none, int] = none()
arg2: Union[none, str] = none()
arg3: Union[none, Dict[str, str]] = none()
def __post_init__(self) -> None:
for k, v in self.__dict__.copy().items():
if isinstance(v, none):
delattr(self, k)
但结果是:
>>> asdict(Bla())
{'arg1': <__main__.none object at 0x7f71bc0159b0>, 'arg2': <__main__.none object at 0x7f71bc015a90>, 'arg3': <__main__.none object at 0x7f71bc015ac8>}
我期待一个空的dict
如果尝试:
>>> a = Bla(None, None, None)
>>> del a.__dict__["arg1"]
>>> asdict(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/(....)/venv/lib/python3.6/site-packages/dataclasses.py", line 1011, in asdict
return _asdict_inner(obj, dict_factory)
File "/home/(...)/venv/lib/python3.6/site-packages/dataclasses.py", line 1018, in _asdict_inner
value = _asdict_inner(getattr(obj, f.name), dict_factory)
AttributeError: 'Bla' object has no attribute 'arg1'
如何以asdict之后可以使用的方式从数据类对象中动态删除属性?
守着星空守着你
哆啦的时光机
相关分类