Re: How do I use python YAMLObject to_yaml and from_yaml?
Kirill Simonov <[email protected]>
| Newsgroups | gmane.text.yaml.general |
|---|---|
| Message-ID | <[email protected]> |
Hi Matthew,
> I've got a subclass of yaml.YAMLObject named Scratch and I want any
> instance of Scratch to be able to render itself as yaml. I figured I
> could just call from_yaml, but this is a classmethod! Why should
> to_yaml be a classmethod? I want to output yaml based on the
> variables on the instance.
to_yaml accepts the parameters cls, dumper, data. Here data is the
instance of the class.
> For Scratch.from_yaml, I can't figure out how to feed it the right
> stuff to get it to take in a string of yaml and make an instance of
> Scratch.
from_yaml doesn't take the string, it takes a YAML node. By the time
from_yaml function is called, the YAML document is already parsed and
converted to a graph structure.
> I know I can use yaml.dump and yaml.load, but I want these to be
> methods on my class.
Note that instances of YAMLObject automatically knows how to render
themselves into YAML so you only need to override to_yaml/from_yaml if
you want to change the way it is rendered.
I don't quite understand what you want exactly, but it seems you just
want a method that converts a Scratch instance to a YAML document. Here
is what you can do
class Scratch(yaml.YAMLObject):
tag = u'!Scratch'
@classmethod
def load(cls, document):
obj = yaml.load(document)
assert isinstance(obj, cls)
return obj
def dump(self):
return yaml.dump(self)
Thanks,
Kirill
------------------------------------------------------------------------------
Open Source Business Conference (OSBC), March 24-25, 2009, San Francisco, CA
-OSBC tackles the biggest issue in open source: Open Sourcing the Enterprise
-Strategies to boost innovation and cut costs with open source participation
-Receive a $600 discount off the registration fee with the source code: SFAD
http://p.sf.net/sfu/XcvMzF8H