[Python-ideas] Customizing format()

Steven D'Aprano steve at pearwood.info
Wed Mar 18 12:45:11 CET 2009


On Wed, 18 Mar 2009 11:25:42 am Raymond Hettinger wrote:
> 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)'


For what was supposed to be a nice, simple way of formatting numbers, it 
sure became confusing. So thank you for the nutshell.

I like this idea, especially if it means we can simplify the 
format_spec. Can we have the format_spec in a nutshell too?


> 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': ','}

Presumably we value compatibility with localeconv()? If not, then 
perhaps a better name for 'thousands_sep' is 'group_sep', on account 
that if you group by something other than 3 it won't represent 
thousands.

Would this allow you to format a float like this?

1,234,567.89012 34567 89012

(group by threes for the integer part, and by fives for the fractional 
part). Or is that out-of-scope for this proposal?


+1 for a conventions dict. Good plan!



-- 
Steven D'Aprano



More information about the Python-ideas mailing list