string formatter %x and a class instance with __int__ cannot handle long

Kenji Noguchi tokyo246 at gmail.com
Thu Jun 21 04:36:42 EDT 2007


2007/6/20, half.italian at gmail.com <half.italian at gmail.com>:
> In your second example y is an instance of class X...not an int.  y.v
> is an int.  Are you hoping it will cast it to an int as needed using
> your method?  If so, I think you need to do so explicitly...ie "%08x"
> % int(y)
>
> ~Sean

I confirmed that "%08x" % int(y) works. And yes, I'm hoping so.
It actually works that way if the v is less than or equal to 0x7ffffffff.
Please try the test script.  It's essentially the same test with
some more print statements.  All but test d-3 appears to be ok.


2007/6/20, Gabriel Genellina <gagsl-py2 at yahoo.com.ar>:
> It is a bug, at least for me, and I have half of a patch addressing it. As
> a workaround, convert explicitely to long before formatting.

I'm interested in your patch.  What's the other half still missing?

Thanks,
Kenji Noguchi


--->8---->8--->8---
#!/usr/bin/env python

class X:
   def __init__(self, v):
       self.v = v
   def __int__(self):
       print "Hey! I'm waken up!"
       return self.v

def test(arg):
   print 1,type(int(arg))
   print 2,"%08x" % int(arg)
   print 3,"%08x" % arg

a = 0x7fffffff
b = X(0x7fffffff)
c = 0x80000000
d = X(0x80000000)

print "----test a----" ; test(a)
print "----test b----" ; test(b)
print "----test c----" ; test(c)
print "----test d----" ; test(d)
--->8---->8--->8---

And here is the result
----test a----
1 <type 'int'>
2 7fffffff
3 7fffffff
----test b----
1 Hey! I'm waken up!
<type 'int'>
2 Hey! I'm waken up!
7fffffff
3 Hey! I'm waken up!
7fffffff
----test c----
1 <type 'long'>
2 80000000
3 80000000
----test d----
1 Hey! I'm waken up!
<type 'long'>
2 Hey! I'm waken up!
80000000
3 Hey! I'm waken up!
Traceback (most recent call last):
 File "<stdin>", line 23, in ?
 File "<stdin>", line 13, in test
TypeError: int argument required



More information about the Python-list mailing list