[Python-ideas] Customizing format()

Raymond Hettinger python at rcn.com
Wed Mar 18 01:25:42 CET 2009


Mark Dickinson's 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:

     DEB = dict(thousands_sep='_')       # style for debugging
     EXT = dict(thousands_sep=',')       # style for external display
     . . .
     format(x, '8.1f', DEB)
     format(y, '8d', EXT)


Raymond 




More information about the Python-ideas mailing list