[Python-ideas] Customizing format()

Raymond Hettinger python at rcn.com
Wed Mar 18 05:56:12 CET 2009


Am curious whether you guys like this proposal?

Raymond

----- Original Message ----- 

[Raymond Hettinger]
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas 




More information about the Python-ideas mailing list