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

Eric V. Smith eric at trueblade.com
Wed Oct 26 19:44:51 EDT 2016


On 10/25/2016 5:37 AM, Serhiy Storchaka wrote:

Classes that doesn't define the format method for custom PEP 3101 formatting inherits it from parents.

Originally the object.format method was designed as [1]: def format(self, formatspec): return format(str(self), formatspec) An instance is converted to string and resulting string is formatted according to format specifier. Later this design was reconsidered [2], and now object.format is equivalent to: def format(self, formatspec): assert formatspec == '' return format(str(self), '') Non-empty format specifier is rejected. But why call format() on resulting string? Why not return resulting string as is? object.format could be simpler (not just implementation, but for understanding): def format(self, formatspec): assert formatspec == '' return str(self) This can change the behaviour in corner case. str(self) can return not exact string, but string subclass with overloaded format. But I think we can ignore such subtle difference. [1] https://www.python.org/dev/peps/pep-3101/ [2] http://bugs.python.org/issue7994

I don't feel strongly about this, one way or the other. As you say, it would take an unusual case to see this behavior:

class S(str): ... def format(self, fmt): ... return 'aha!' ... class O: ... def str(self): ... return S() ... format(O(), '') 'aha!'

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?

Eric.



More information about the Python-Dev mailing list