我有一个typing.NamedTuple
我想转换成dict
,这样我就可以通过字典解包传递到函数中:
def kwarg_func(**kwargs) -> None:
print(kwargs)
# This doesn't actually work, I am looking for something like this
kwarg_func(**dict(my_named_tuple))
实现这一目标的最具Python风格的方式是什么?我正在使用Python 3.8+
更多详细信息
下面是一个例子NamedTuple
,可以使用:
from typing import NamedTuple
class Foo(NamedTuple):
f: float
b: bool = True
foo = Foo(1.0)
尝试kwarg_func(**dict(foo))
会引发TypeError
:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
根据this post on ^{_asdict()
工程:
kwarg_func(**foo._asdict())
{'f': 1.0, 'b': True}
然而,既然_asdict
是私有的,我想知道,有没有更好的办法
使用
._asdict
._asdict
是非私有的。它是API的一个公开的、有文档记录的部分From the docs:相关问题 更多 >
编程相关推荐