[Python-Dev] Default formatting (original) (raw)

Steve Dower steve.dower at python.org
Thu Oct 27 12:59:39 EDT 2016


On 27Oct2016 0251, Serhiy Storchaka wrote:

On 27.10.16 02:44, Eric V. Smith wrote:

But on the other hand, the existing behavior is well specified and has been around since object.format was added. I'm not sure it needs changing. What's the harm in leaving it? More complicated code. And maybe this behavior is less intuitive. It contradicts the documentation. From the documentation of the format() builtin [1]: "The default formatspec is an empty string which usually gives the same effect as calling str(value)." From the description of the format specification mini-language [2]: "A general convention is that an empty format string ("") produces the same result as if you had called str() on the value." [1] https://docs.python.org/3/library/functions.html#format [2] https://docs.python.org/3/library/stdtypes.html#str.format

The only point where this bothers me is that alignments don't work:

class F: pass ... '{}'.format(F()) '<__main__.F object at 0x000002148AFE6B70>' '{:100}'.format(F()) Traceback (most recent call last): File "", line 1, in TypeError: non-empty format string passed to object.format '{:<100}'.format(F()) Traceback (most recent call last): File "", line 1, in TypeError: non-empty format string passed to object.format

You need to explicitly include '!s' to be able to align it, which then means overriding format in that class later won't have any effect.

'{!s:<100}'.format(F()) '<__main__.F object at 0x000002148AFEE240> '

Having the default format behave like this makes me happiest:

... def format(self, fmt): ... return format(str(self), fmt)

My 2c. YMMV. etc.

Cheers, Steve



More information about the Python-Dev mailing list