With file xx.py:
class Foo(object):
def __init__(self, x):
self.x = x
def __long__(self):
return long(self.x)
def __float__(self):
return float(self.x)
y = Foo(22)
print '%d' % y
print '%d' % y
Interactive mode:
$ python -V
Python 2.6.7
$ python -i xx.py
22
22
>>>
TypeError: int() argument must be a string or a number, not 'Foo'
>>> '%d' % y
'22'
>>> '%d' % y
TypeError: int() argument must be a string or a number, not 'Foo'
>>> '%d' % y
'22'
>>> '%d' % y
TypeError: int() argument must be a string or a number, not 'Foo'
Why does it alternate between printing '22' and raising a TypeError?
Why does it raise an error on the first carriage return (with no input)?
Thanks.
Looks like a bug in python! My guess is it's caused by some leftover cruft from the old string-based exceptions.
The hexadecimal stuff is a red herring, you can also get strange behaviour with simply assigning y = Foo(1) and just using '%d' % y will exhibit the funny toggling stuff.
You should get an TypeError at the first print '0x%x' % y in your script, because that part is not well-defined. But somehow the result gets coerced, and it looks like a string-based exception somehow gets...missed, when it probably should have been turned into a TypeError.
If this string substitution stuff is buggy then it's one more reason to move to the preferred new method for string formatting, e.g. print '{0:x}'.format(22)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With