Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding comments to dumped python classes #56

Open
the-moog opened this issue Jul 6, 2021 · 0 comments
Open

Adding comments to dumped python classes #56

the-moog opened this issue Jul 6, 2021 · 0 comments

Comments

@the-moog
Copy link

the-moog commented Jul 6, 2021

Line 830 of representer.py hints that it's possible to add comments to serialisation of python object instances.

Consider the following code. How would I modify it so that the resulting yaml is commented to look like this:

!C
# Documentation for  class C
data: C
contents: !B
# Documentation for class B
  data: B
  contents: !A
# Documentation for class A
    data: A
    contents:

Is that already possible or would that be a new feature?

import ruamel.yaml
from ruamel.yaml import yaml_object
from io import StringIO
import contextlib
import sys


@contextlib.contextmanager
def uncloseable(fd):
    """
    Context manager which turns the fd's close operation to no-op for the duration of the context.
    """
    close = fd.close
    fd.close = lambda: None
    yield fd
    fd.close = close


def get_obj_as_yaml(yaml_inst, object):
    # Use StringIO to capture the yaml output
    s = StringIO()
    with uncloseable(s):
        yaml_inst.dump(object, s)

    yaml_text = s.getvalue()
    s.close()
    return yaml_text


yaml = ruamel.yaml.YAML()

class SomeData:
    def __init__(self, data):
        self.data = data
        self.contents = None

@yaml_object(yaml)
class A(SomeData):
    """This is an A object"""
    def __init__(self):
        super().__init__("A")


@yaml_object(yaml)
class B(SomeData):
    """This is a B object"""
    def __init__(self):
        super().__init__("B")
        self.contents = A()


@yaml_object(yaml)
class C(SomeData):
    """This is a C object"""
    def __init__(self):
        super().__init__("C")
        self.contents = B()


# Create an instance of the top level object
# which has other object instances inside
instance = C()

# Serialise the objects tree as yaml
text = get_obj_as_yaml(yaml, instance)
sys.stdout.write(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant