Eric V. Smith added the comment: >> >> I think that specifying __format__() would be best, except then you need to >> decide what sort of format specification language you want to support, and >> deal with all of the implementation details. Or, maybe just have Enum's >> __format__ be: >> >> def __format__(self, fmt): >> return format(str(self), fmt) >> >> which makes the format specification language match str's. > > I disagree. A subclass shouldn't have to write code to provide the /same/ > behavior as its superclass, just code for > different behavior. In the cases of > '%d' % int_subclass > or > '{:d}'.format(int_subclass) > > str should be smart enough to actually produce the numeric value, not rely on > the subclass' __repr__.
I'm not sure which "str" you mean here: "str should be smart enough to actually produce the numeric value". For the format version, what gets called is: int_subclass.__format__('d'), which is int.__format__(int_subclass, 'd'), which produces '1', assuming int(int_subclass) is 1. So, there's no "str" involved anywhere, except the one on which .format() is called ('{:d}'), and it doesn't know about the types of any arguments or what the format specifiers mean, so it can't make any decisions. Which is why it's easier to think of this in terms of: format(int_subclass, 'd') instead of: '{:d}'.format(int_subclass) It's int_subclass, and only int_subclass, that gets to decide what the format specifier means. We can either let it fall back to int.__format__ (the default), or str.__format__ (which I suggest above), or it can do it's own custom thing with the format specifier. ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue18738> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com