我想将包含 IP 地址(作为
ipaddress.IPv4Network
对象)的字典转储为 YAML。按照文档,我尝试了以下操作:
import ipaddress
import yaml
def address_representer(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', str(data))
yaml.add_representer(ipaddress.IPv4Network, address_representer)
print(yaml.safe_dump({'network': ipaddress.IPv4Network('192.168.1.0/24')}))
但这失败了:
[...]
File "/home/lars/.local/lib/python3.9/site-packages/yaml/representer.py", line 231, in represent_undefined
raise RepresenterError("cannot represent an object", data)
yaml.representer.RepresenterError: ('cannot represent an object', IPv4Network('192.168.1.0/24'))
我做错了什么?
传递了最后一条评论,我相信以下内容可以解决这个答案:
import ipaddress
import yaml
def address_representer(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', str(data))
yaml.SafeDumper.add_representer(ipaddress.IPv4Network, address_representer)
print(yaml.safe_dump({'network': ipaddress.IPv4Network('192.168.1.0/24')}))