new string-formatting preferred? (was "What is this syntax ?")

Tim Chase python.list at tim.thechases.com
Tue Jun 21 19:02:03 EDT 2011


On 06/21/2011 05:19 PM, Terry Reedy wrote:
> On 6/21/2011 7:33 AM, Tim Chase wrote:
>>>>> <URL:http://docs.python.org/library/stdtypes.html#str.format>
>>>>
>>>> Is there a good link to a thread-archive on when/why/how .format(...)
>>>> became "preferred to the % formatting"?
>>>
>>> That is a controversial statement.
>>
>> I'm not sure whether you're "controversial" refers to
>>
>> - the documentation at that link,
>
> I meant the preceding statement (derived from the linked source, but
> that is not important) that .format is preferred to %.

I guess then with all the contention, having such a vocal 
preference in the docs (even if tempered by "in new code") seems 
to unnecessarily polarize when I find myself very "meh" in either 
direction.

>>> multi_warn = '''\
>>> Warning: testing multiple {0}s against an iterator will only test
>>> the first {0} unless the iterator is reiterable; most are not.'''.format
>>> ...
>>> print(multiwarn('function'))
>>> ...
>>> print(multiwarn('iterator'))
>>
>> Does the gotcha of a non-restarting iterator
>
> Huh? What iterator?

Your string-body text warns about behavior regarding iterators. 
I was thrown by your warning.

>> The other new feature I saw was the use of __format__()
>
> Suppose one had a Money class with currency and decimal amount fields.
> .__str__ can add a currency symbol (before or after as appropriate) but
> has to use a standard format for the amount field. .__float__ can be
> post-processed according to a %...f spec, but cannot include a currency
> symbol. Money.__format__(self,spec) can format the amount at it wishes,
> including its rounding rules, *and* add a currency symbol.

A Money class was one of the first things I thought of, but 
figured that would be better relegated to an i18n wrapper if you 
wanted it.  Such a wrapper would handle currency-symbol choice & 
positioning positioning (before vs. after; relation to the +/-; 
optional characters for thousands-separators and decimal 
separators; and partitioning at thousands-or-other-multiples, etc).

> Or suppose one has a multi-precision float. %80.40f will require an mpf
> instance to appoximate itself as a float, possibly with error.
> mpg.__format__ should be able to do better.

This case makes a better argument, showing me some new value 
added by __format__().

-tkc






More information about the Python-list mailing list