Re: [Q] How to compose, serialize, and emit in PyYAML?

Kirill Simonov <[email protected]>
Newsgroups gmane.text.yaml.general
Message-ID <[email protected]>
Makoto Kuwata wrote:
> Hi,
> I'm investigating PyYAML 3.05 and have some questions.
> 
> Q1. How to compose nodes from event list?
> Q2. How to serialize node into event list?
> Q3. How to emit event list into stram?

PyYAML has no direct support for Q1 and Q2. For Q3, you may use:

yaml.emit(events)

Basically, PyYAML only supports serializing events/nodes/objects to the 
output YAML stream and deserializing tokens/events/nodes/objects from 
the input YAML stream.  However it is relatively easy to write 
nodes->events and events->nodes converters using existing PyYAML 
infrastructure.

For Q1 (events to nodes):

class EventsToNodes(yaml.composer.Composer, yaml.resolver.Resolver):

     def __init__(self, events):
         super(EventsToNodes, self).__init__()
         if isinstance(events, list):
             events = iter(events)
         self.events = events
         self.current_event = None

     def check_event(self, *choices):
         if self.current_event is None:
             self.current_event = self.events.next()
         if not choices:
             return True
         for choice in choices:
             if isinstance(self.current_event, choice):
                 return True
         return False

     def peek_event(self):
         if self.current_event is None:
             self.current_event = self.events.next()
         return self.current_event

     def get_event(self):
         if self.current_event is None:
             self.current_event = self.events.next()
         value = self.current_event
         self.current_event = None
         return value

node = yaml.compose(events, Loader=EventsToNodes)
print node

For Q2 (nodes to events):

class NodesToEvents(yaml.serializer.Serializer, yaml.resolver.Resolver):

     def __init__(self, events, **parameters):
         super(NodesToEvents, self).__init__()
         self.events = events

     def emit(self, event):
         self.events.append(event)

events = []
yaml.serialize(node, events, Dumper=NodesToEvents)
print events


Thanks,
Kirill

-------------------------------------------------------------------------
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://ad.doubleclick.net/clk;164216239;13503038;w?http://sf.net/marketplace
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.