[Python-3000] string.Formatter class

Eric Smith eric+python-dev at trueblade.com
Thu Aug 30 12:55:18 CEST 2007


Talin wrote:
> Eric Smith wrote:
>> Eric Smith wrote:
>>> Jim Jewett wrote:
>>
>>>> but you might want to take inspiration from the "tail" of an
>>>> elementtree node, and return the field with the literal next to it as
>>>> a single object.
>>>>
>>>>     (literal_text, field_name, format_spec, conversion)
>>> I think I like that best.
>>
>> I implemented this in r57641.  I think it simplifies things.  At least,
>> it's easier to explain.
> 
> Actually...I'm in the middle of writing the docs for the reference 
> manual, and I'm finding this a little harder to explain. Not *much* 
> harder, but a little bit.

I think it's easier because it's always:
Output the (possibly zero length) literal text
then, format and output the field, if field_name is non-None

But I'm flexible.

> I would probably have gone with one of the following:
> 
>    # Test for str vs tuple
>    literal_text
>    (field_name, format_spec, conversion)
> 
>    # Test for length of the tuple
>    (literal_text)
>    (field_name, format_spec, conversion)
> 
>    # Test for 'None' format_spec
>    (literal_text, None, None)
>    (field_name, format_spec, conversion)

If you want to change, I'd go with this last one.  Actually, I had it 
working this way, once, but I thought that re-using the first item 
(which I called literal_or_field_name) was too obscure.

> However, I'm not adamant about this - it's up to you what you like best, 
> I'll come up with a way to explain it. Also I recognize that your method 
> is probably more efficient for the nominal use case -- less tuple creation.

Also, it requires fewer iterations.  Instead of 2 iterations per 
field_name in the string:
   yield literal
   yield field_name, format_spec, conversion

it's just one:
   yield literal, field_name, format_spec, conversion

Like you, I don't feel strongly about which way it works.  But the Jim's 
suggestion that it's how elementtree works sort of convinced me.

> Also I wanted to ask: How about making the built-in 'format' function 
> have a default value of "" for the second argument? So I can just say:
> 
>    format(x)
> 
> as a synonym for:
> 
>    str(x)

Makes sense to me.  It would really call x.__format__(''), which the PEP 
suggests (but does not require) be the same as str(x).

>> Due to an optimization dealing with escaped braces, it's possible for
>> (literal, None, None, None) to be returned more than once.  I don't
>> think that's a problem, as long as it's documented.  If you look at
>> string.py's Formatter.vformat, I don't think it complicates the
>> implementation at all.
> 
> It's also possible for the literal text to be an empty string if you 
> have several consecutive format fields - correct?

Correct.  The literal text will always be a zero-or-greater length string.



More information about the Python-3000 mailing list