Enumerating formatting strings

Bengt Richter bokr at oz.net
Tue Apr 19 02:35:06 EDT 2005


On Mon, 18 Apr 2005 16:24:39 -0400, Steve Holden <steve at holdenweb.com> wrote:

>I was messing about with formatting and realized that the right kind of 
>object could quite easily tell me exactly what accesses are made to the 
>mapping in a string % mapping operation. This is a fairly well-known 
>technique, modified to tell me what keys would need to be present in any 
>mapping used with the format.
>
<snip code>
>I've been wondering whether it's possible to perform a similar analysis 
>on non-mapping-type format strings, so as to know how long a tuple to 
>provide, or whether I'd be forced to lexical analysis of the form string.
>
When I was playing with formatstring % mapping I thought it could
be useful if you could get the full format specifier info an do your own
complete formatting, even for invented format specifiers. This could be
done without breaking backwards compatibility if str.__mod__ looked for
a __format__ method on the other-wise-mapping-or-tuple-object. If found,
it would call the method, which would expect

    def __format__(self,
        ix,    # index from 0 counting  every %... format
        name,  # from %(name) or ''
        width, # from %width.prec
        prec,  # ditto
        fc,    # the format character F in %(x)F
        all    # just a copy of whatever is between % and including F
    ): ...

This would obviously let you handle non-mapping as you want, and more.

The most popular use would probably be intercepting width in  %(name)<width>s
and doing custom formatting (e.g. centering in available space) for the object
and returning the right size string.

Since ix is an integer and doesn't help find the right object without the normal
tuple, you could give your formatting object's __init__ method keyword arguments
to specify arguments for anonymous slots in the format string, conventionally
naming them a0, a1, a2 etc. Then later when you get an ix with no name, you could
write self.kw.get('%as'%ix) to get the value, as in use like
     '%(name)s %s' % Formatter(a1=thevalue) # Formatter as base class knows how to do name lookup

Or is this just idearrhea?
      
Regards,
Bengt Richter



More information about the Python-list mailing list