[英]python dataclass asdict ignores attributes without type annotation
Python documentation explains how to use dataclass
asdict
but it does not tell that attributes without type annotations are ignored: Python 文档解释了如何使用
dataclass
asdict
但没有说明没有类型注释的属性会被忽略:
from dataclasses import dataclass, asdict
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d = "nope"
c = C(5)
asdict(c)
# this returns
# {'a': 5, 'b': 3, 'c': 'yes'}
# note that d is ignored
How can I make d
attribute appear in the returned dict without implementing the function myself?如何在不自己实现函数的情况下使
d
属性出现在返回的字典中?
You can use Any
as type annotation.您可以使用
Any
作为类型注释。 For example:例如:
from typing import Any
from dataclasses import dataclass, asdict
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d : Any = "nope"
c = C(5)
asdict(c)
# this returns
# {'a': 5, 'b': 3, 'c': 'yes', 'd': 'nope'}
# Now, d is included as well!
A cheesy and somewhat unprofessional way is to annotate it with any random string value.一种俗气且有点不专业的方法是用任何随机字符串值对其进行注释。
So, for example:因此,例如:
from dataclasses import dataclass, asdict
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d: 'help,, i dunno how [a]ny of this w@rks!!' = "nope"
c = C(5)
print(asdict(c))
# this returns
# {'a': 5, 'b': 3, 'c': 'yes', 'd': 'nope'}
With some thought, this can actually be simplified down to:经过一番思考,这实际上可以简化为:
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d: ... = "nope"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.