[Python-ideas] Custom format() proposal redux

Raymond Hettinger python at rcn.com
Wed Apr 8 19:24:11 CEST 2009


The original proposal was well-received but it didn't make provisions to handle str.format().
Here is the revised proposal.  Only the last paragraph is new.


Raymond

-------------------------------------------------------------------


Mark Dickinson's decimal test code suggested a good, extensible approach to the problem.  Here's the idea in a nutshell:

  format(value, format_spec='', conventions=None)
     'calls value.__format__(format_spec, conventions)'

Where conventions is an optional dictionary with formatting control values.  Any value object can accept custom controls, but the 
names for standard ones would be taken from the standards provided by localeconv():

  {
   'decimal_point': '.',
   'grouping': [3, 0],
   'negative_sign': '-',
   'positive_sign': '',
   'thousands_sep': ','}

The would let you store several locales using localeconv() and use them at will, thus solving the global variable and threading 
problems with locale:

     import locale
     loc = locale.getlocale() # get current locale
     locale.setlocale(locale.LC_ALL, 'de_DE')
     DE = locale.localeconv()
     locale.setlocale(locale.LC_ALL, 'en_US')
     US = locale.localeconv()
     locale.setlocale(locale.LC_ALL, loc) # restore saved locale

     . . .

     format(x, '8,.f', DE)
     format(y, '8,d', US)

It also lets you write your own conventions on the fly:

     DEBUG = dict(thousands_sep='_')       # style for debugging
     EXTERN = dict(thousands_sep=',')      # style for external display

     . . .

     format(x, '8.1f', DEBUG)
     format(y, '8d', EXTERN)

The dictionaries can be registered for use with the mini-formatting language:

    locale.setlocale(locale.LC_ALL, 'en_US')
    str.format.register(US=locale.localeconv())
    str.format.register(HY=dict(thousands_sep='-'))

     . . .

    'Nigerian President will forward {0:,d!US} to your account'.format(10000000)
    format(y, ',d!HY')
    format(z, ',d!US')



More information about the Python-ideas mailing list