Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate error and no-error in python interactive mode

Tags:

python

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.

like image 718
user650654 Avatar asked Sep 01 '26 14:09

user650654


1 Answers

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)

like image 182
wim Avatar answered Sep 03 '26 04:09

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!