Ticket #214 (new enhancement)

Opened 2 years ago

Last modified 44 years ago

align map-values at dump

Reported by: az@… Owned by: xi
Priority: normal Component: pyyaml
Severity: normal Keywords:


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.
import yaml
from yaml.nodes import ScalarNode

class Dumper_MapAlignValues( object):
    'inherit + Dumper'

    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

    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)
       = ( parent._keywidth - len( index.value ),
        return yaml.Dumper.serialize_node( self, node, parent, index)

    def choose_scalar_style(self):
        alignindent = None
        if isinstance(, tuple):
            alignindent, =
        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)
        return r

class Dumper( yaml_align.Dumper_MapAlignValues, yaml.Dumper):

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



Add a comment

Modify Ticket

Change Properties
<Author field>
as new
as The resolution will be set. Next status will be 'closed'
to The owner will be changed from xi. Next status will be 'new'
The owner will be changed from xi to anonymous. Next status will be 'assigned'

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.