Format specification mini-language for list joining

Tobia Conforto tobia.conforto at gmail.com
Sat Nov 10 16:11:10 EST 2012


Kwpolska wrote:
> > out = 'Temperatures: {0:", ":.1f} Celsius'.format(temps)
> 
> [...] your format is cryptic.

Thank you for your criticism, I'll think it over. The reason I find it readable (-enough) is because even without knowing what format language is supported by the temps object, you can tell that "it" (the 0th argument in this case) is what's going to be serialized in that place.

Everything after the first colon is game anyways, meaning you'll have to look it up in the docs, because it's defined somewhere in the class hierarchy of the object being serialized. The fact that 99% of classes don't define a __format__ method and thus fall back on object's implementation, with it's alignment and padding operators, is IMHO irrelevant. It's still something you can't pretend to know out of the box, because it's supposed to be customizable by classes.

Knowing this, if you know that the temps object is a list of floats, then I think it'd be pretty obvious what the ", " and the :.1f should do.

> As I said, it’s hard to even get this one changed 
> because str.format is 4 years old.

Again, I beg to differ. I'm not proposing any change to format (that would be madness). What I'm proposing is the addition of a customized __format__ method to a few types, namely lists and sequences, that currently lack it (as do 99% of classes) and fall back to object's implementation. Which is kind of pointless with lists, as joining is by far the thing most often done to them when formatting.

Tobia



More information about the Python-list mailing list