Pyyaml Comment Emitter
Join the DZone community and get the full member experience.
Join For FreeHere 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: Ticket 114
#!/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
Opinions expressed by DZone contributors are their own.
Comments