[Python-Dev] Format factories (was Re: sWAPcASE Was: transform() and untransform() methods, and the codec registry)

Nick Coghlan ncoghlan at gmail.com
Fri Dec 10 01:26:09 CET 2010


On Fri, Dec 10, 2010 at 9:29 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On Thu, 09 Dec 2010 18:10:38 -0500
> Eric Smith <eric at trueblade.com> wrote:
>> If we're looking to reduce the number of methods on str, I wouldn't mind
>> seeing center() and zfill() also go away, since they're trivially
>> replaced by format().
>
> Well, it's only trivial when you know format()'s wicked mini-language by
> heart :/  center() is easy and obvious. zfill() is arguably a bit too
> specialized.

I've occasionally wondered if string formatting [1] and the struct
module [2] would benefit from format building functions that made them
easier to use without necessarily learning the cryptic mini-languages
off by heart.

For example, a "string.make_format_spec" function might have a signature like:

def make_format_spec(fill=None, align=None, sign=None, width=None,
precision=None, display_type='s', alternate=False, commas=False,
numeric_case=None)

"align" would accept not only the actual format symbols ('<', '>',
'=', '^'), but also the corresponding names ('left', 'right',
'numeric', 'center').

"numeric_case" would accept None, 'upper' or 'lower' (affecting the
formatting of hex and floating point values). If the stated numeric
case differs from that specified by the display type, raise a
ValueError. For an unspecified numeric case, the affected display
types would default to 'lower'.

Similarly, "display_type" would accept long names in addition to the
character codes:

's': 'str'
'b': 'binary'
'c': 'chr'
'd': 'int'
'o': 'octal'
'x', 'X': 'hex' (numeric case controls display of digits A-F)
'n': 'locale'
'e', 'E': 'exponent' (numeric case controls display of exponent as
well as infinite and NaN values)
'f', 'F': 'float' (numeric case controls display of exponent as well
as infinite and NaN values)
'g', 'G': 'general' (numeric case controls display of exponent as well
as infinite and NaN values)
'%': 'percent' (numeric case controls display of exponent as well as
infinite and NaN values)

There could also be a corresponding parse_format_spec that produced a
named tuple with the appropriate details.

Cheers,
Nick.

[1] http://docs.python.org/dev/library/string#format-specification-mini-language
[2] http://docs.python.org/dev/library/struct#format-strings

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list