Modify

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:
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

View

Add a comment

Modify Ticket

Change Properties
<Author field>
Action
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'
Author


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

 
Note: See TracTickets for help on using tickets.