如何修复 Python yaml.representer.RepresenterError: ('cannot represent an object', defaultdict(<class 'list'>, ....
问题:
你正在尝试 yaml.safe_dump() 一个是(或包含)defaultdict 的对象,例如:
yaml_fix.py
import yaml
import collections
yaml.safe_dump(collections.defaultdict(list))这会导致以下异常:
yaml_repr_error.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/uli/.local/lib/python3.10/site-packages/yaml/__init__.py", line 269, in safe_dump
return dump_all([data], stream, Dumper=SafeDumper, **kwds)
File "/home/uli/.local/lib/python3.10/site-packages/yaml/__init__.py", line 241, in dump_all
dumper.represent(data)
File "/home/uli/.local/lib/python3.10/site-packages/yaml/representer.py", line 27, in represent
node = self.represent_data(data)
File "/home/uli/.local/lib/python3.10/site-packages/yaml/representer.py", line 58, in represent_data
node = self.yaml_representers[None](self, data)
File "/home/uli/.local/lib/python3.10/site-packages/yaml/representer.py", line 231, in represent_undefined
raise RepresenterError("cannot represent an object", data)
yaml.representer.RepresenterError: ('cannot represent an object', defaultdict(<class 'list'>, {}))解决方案
你需要添加自定义表示器来隐式将 defaultdict 转换为 dict。
在运行 yaml.safe_dump() 之前,添加以下行:
represent_defaultdict_fix.py
import collections
from yaml.representer import Representer
yaml.SafeDumper.add_representer(collections.defaultdict, Representer.represent_dict)现在,yaml.safe_dump() 调用应该完美工作:
yaml_safe_dump_defaultdict_fixed.py
yaml.safe_dump(collections.defaultdict(list)) # Returns'{}\n'Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow