尝试将自定义表示器添加到 Python yaml 模块时出现意外行为?

问题描述 投票:0回答:1

我想将包含 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'))

我做错了什么?

python serialization yaml pyyaml
1个回答
0
投票

传递了最后一条评论,我相信以下内容可以解决这个答案:

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')}))
© www.soinside.com 2019 - 2024. All rights reserved.