1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Unexpected behavior trying to add a custom representer to Python yaml module?

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I want to dump a dictionary containing ip addresses (as ipaddress.IPv4Network objects) as YAML. Following the docs, I tried the following:

    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')}))


    But this fails with:

    [...]
    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'))


    What am I doing wrong?

    Continue reading...

Compartilhe esta Página