[Python-Dev] PEP 461 - Adding % and {} formatting to bytes (original) (raw)
Ethan Furman ethan at stoneleaf.us
Fri Jan 17 17:07:03 CET 2014
- Previous message: [Python-Dev] PEP 461 - Adding % and {} formatting to bytes
- Next message: [Python-Dev] PEP 461 - Adding % and {} formatting to bytes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 01/16/2014 11:47 PM, Steven D'Aprano wrote:
On Thu, Jan 16, 2014 at 08:23:13AM -0800, Ethan Furman wrote:
As I understand it, str.format will call the object's format. So, for example, if I say:
u'the value is: %d' % myNum(17) then it will be myNum.format that gets called, not int.format; I seem to have missed something, because I am completely confused... Why are you talking about str.format and then show an example using % instead?
Sorry, PEP 46x fatigue. :/
It should have been
u'the value is {:d}'.format(myNum(17))
and yes I meant the str type.
%d calls str, not format. This is in Python 3.3:
py> class MyNum(int): ... def str(self): ... print("Calling MyNum.str") ... return super().str() ... def format(self): ... print("Calling MyNum.format") ... return super().format() ... py> n = MyNum(17) py> u"%d" % n Calling MyNum.str '17'
And that's a bug we fixed in 3.4:
Python 3.4.0b1 (default:172a6bfdd91b+, Jan 5 2014, 06:39:32) [GCC 4.7.3] on linux Type "help", "copyright", "credits" or "license" for more information.
--> class myNum(int): ... def int(self): ... return 7 ... def index(self): ... return 11 ... def float(self): ... return 13.81727 ... def str(self): ... print('str') ... return '1' ... def repr(self): ... print('repr') ... return '2' ... --> '%d' % myNum() '0' --> '%f' % myNum() '13.817270'
After all, consider:
'%d' % True '1' '%s' % True 'True'
So, in fact, on subclasses str should not be called to get the integer representation. First we do a conversion to make sure we have an int (or float, or ...), and then we call str on our tried and trusted genuine core type.
The worst solution would be to completely ignore MyNum.str. That's a nasty violation of the Principle Of Least Surprise, and will lead to confusion ("why isn't my class' str method being called?")
Because you asked for a numeric representation, not a string representation [1].
--
Ethan
[1] for all the gory details, see: http://bugs.python.org/issue18780 http://bugs.python.org/issue18738
- Previous message: [Python-Dev] PEP 461 - Adding % and {} formatting to bytes
- Next message: [Python-Dev] PEP 461 - Adding % and {} formatting to bytes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]