DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Pyyaml Comment Emitter

02.13.2009
| 3803 views |
  • submit to reddit
        Here is an extension of the emitter to allow comments at the end of lines.
Not perfect, but shows how it could be done.

More information: <a href="http://pyyaml.org/ticket/114">Ticket 114</a>

#!/bin/env python

import yaml

class CommentEvent(yaml.Event):
  def __init__(self,message):
    self.message = message
  def __repr__(self):
    return '%s(%r)' % (self.__class__.__name__,self.message)

class MyDumper(yaml.Dumper):
  def __init__(self,*args,**kwargs):
    self.comments = []
    self.comment_column = 25
    if 'comment_column' in kwargs:
      self.comment_column = kwargs.pop('comment_column')
    super(MyDumper,self).__init__(*args,**kwargs)
  def add_comment(self,message):
    self.comments.extend(message.splitlines())
  def emit(self,event):
    if isinstance(event,CommentEvent):
      self.add_comment(event.message)
    else:
      super(MyDumper,self).emit(event)
  def write_line_break(self,data=None):
    if self.comments:
      self.indents.append(self.indent)
      self.indent = max(self.comment_column,self.column + 2)
      self.indention = True
      comments = self.comments[:]
      del self.comments[:]
      for line in comments:
        self.write_indent()
        self.write_indicator('# %s' % (line,),True)
      self.indent = self.indents.pop()
    super(MyDumper,self).write_line_break(data)

Example:

document = """\
---
name: Cave spider
hp: [2, 6]
ac: 16
attacks: [BITE, HURT]
"""
events = list(yaml.parse(document))
events[5:5] = [CommentEvent("foo")]
events[11:11] = [CommentEvent("bar")]
events[19:19] = [CommentEvent("baz")]

print yaml.emit(events,Dumper=MyDumper)

Prints:

---                      # foo
name: Cave spider
hp: [2, 6]               # bar
ac: 16
attacks: [BITE, HURT]    # baz