Search code examples
python-3.xyamlnetplanpython-netifaces

How remove metaclasses info when writing to yaml?


import netifaces
import netaddr
import yaml


class Ethernet(yaml.YAMLObject):
    def __init__(self, addresses, gateway4, mtu, nameservers):
        self.nameservers = nameservers
        self.mtu = mtu
        self.gateway4 = gateway4
        self.addresses = addresses

I am trying to write this class to a yum file:

with open("/home/netplan.yaml", "w") as file:
    yaml.dump(document, file, default_flow_style=False)

I get this result:

!!python/object:__main__.Netplan
network: !!python/object:__main__.Network
  ethernets:
    docker0: !!python/object:__main__.Ethernet
      addresses:
      - 172.26.0.1/16
      gateway4: 1.1.1.1
      mtu: 9000

How is it possible to remove all meta information like !!python/object:main. from a yaml file?


Solution

  • I have no idea what a yum is but I will assume that you're talking about YAML.

    You can define a class attribute yaml_tag to control the tag used when serializing your class. If you set it to the default tag for mappings, it won't be written:

    from yaml.resolver import BaseResolver
    
    class Ethernet(yaml.YAMLObject):
        yaml_tag = BaseResolver.DEFAULT_MAPPING_TAG
    
        def __init__(self, addresses, gateway4, mtu, nameservers):
            self.nameservers = nameservers
            self.mtu = mtu
            self.gateway4 = gateway4
            self.addresses = addresses
    

    However note that if you do this, you can't load the YAML into this class again.

    If you don't have control over the types you dump, you can register a custom representer for them instead:

    yaml.add_representer(Foo, lambda dumper, data: dumper.represent_mapping(
        BaseResolver.DEFAULT_MAPPING_TAG, data.__dict__))