• Project Info
  • Language
  • Python
  • License
  • MIT
  • Version Released
  • Jan. 20, 2021
  • Docs Built
  • May 30, 2021
  • Latest Version
  • master
  • Collaborators
  • admin
  • Tags
  • yaml

Function represent_yaml_object

Synopsis

def represent_yaml_object(self, tag, data, cls, flow_style=None)

Description

No description yet.

Source

Lines 223-229 in lib3/yaml/representer.py.

def represent_yaml_object(self, tag, data, cls, flow_style=None):
    if hasattr(data, '__getstate__'):
        state = data.__getstate__()
    else:
        state = data.__dict__.copy()
    return self.represent_mapping(tag, state, flow_style=flow_style)


Discussions (1)

RobertMela 1 month ago 0

Dumping an object using a custom yaml tag in situations where it's hard or not possible to inherit from YAMLObject or override __repr__

import yaml

class MyDumper(yaml.Dumper): pass

class MyObjectWrapper:
    """
    Wrapper class for dumping any object with a custom tag via Dumper.represent_yaml_object.
    value must be an object that can be yaml dumped
    """

    def __init__(self, value):
        self.value = value

def my_custom_object_representer(dumper, data):
    return dumper.represent_yaml_object(
        "!MyCustomTag",
        MyObjectWrapper( transmogrify(data) ), # or data.transmogrify()
        MyObjectWrapper,
    )

MyDumper.add_representer(MyHardToRepresentClass, my_custom_object_representer)

# Result is:
#
#  !MyCustomTag:
#      value: my_transmogrified_value
#



Add Discussion as Guest

Log in