Modify ↓
Ticket #214 (new enhancement)
align map-values at dump
| Reported by: | az@… | Owned by: | xi |
|---|---|---|---|
| Priority: | normal | Component: | pyyaml |
| Severity: | normal | Keywords: | |
| Cc: |
Description
here something that aligns values of maps in vertical column (depending on longest key, or u can change the logic). it's somewhat patchwork, but works.
#yaml_align.py
import yaml
from yaml.nodes import ScalarNode
class Dumper_MapAlignValues( object):
'inherit + Dumper'
#Representer.represent_mapping
def represent_mapping(self, tag, mapping, flow_style=None):
node = yaml.Dumper.represent_mapping( self, tag, mapping, flow_style)
node._keywidth = 0
if mapping:
keys = [ k for k,v in node.value]
simplekeys = sum( isinstance( k,ScalarNode) for k in keys) == len( node.value)
if simplekeys:
node._keywidth = max( len( str(k.value)) for k in keys)
return node
#Serializer.serialize_node
def serialize_node(self, node, parent, index):
if (node not in self.serialized_nodes
and isinstance( node, ScalarNode)
and getattr( parent, '_keywidth', None) #mapping with _keywidth
and index is not None #this=value, index=key in (key,value)
):
node.style = ( parent._keywidth - len( index.value ), node.style)
return yaml.Dumper.serialize_node( self, node, parent, index)
#Emitter.choose_scalar_style
def choose_scalar_style(self):
alignindent = None
if isinstance( self.event.style, tuple):
alignindent, self.event.style = self.event.style
r = yaml.Dumper.choose_scalar_style( self)
if alignindent is not None and r in ['', "'", '"']:
data = ' '*alignindent
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
return r
'''usage:
class Dumper( yaml_align.Dumper_MapAlignValues, yaml.Dumper):
pass
tt = '''
one: 1
two: 2
three: 3
four: 4
eleven: 11
'''
dd = yaml.load( tt)
print yaml.dump( dd, default_flow_style= False, Dumper= Dumper)
eleven: 11
four: 4
one: 1
three: 3
two: 2
Attachments
Note: See
TracTickets for help on using
tickets.
