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

K

Kenji Noguchi

Hi

I'm using Python 2.4.4 on 32bit x86 Linux. I have a problem with printing
hex string for a value larger than 0x800000000 when the value is given to
% operator via an instance of a class with __int__(). If I pass a long value
to % operator it works just fine.

Example1 -- pass a long value directly. this works.'80000000'

Example2 -- pass an instance of a class with __int__().... def __init__(self, v):
.... self.v = v
.... def __int__(self):
.... return self.v
....Traceback (most recent call last):

The behavior looks inconsistent. By the way __int__ actually
returned a long type value in the Example2. The "%08x" allows
either int or long in the Example1, however it accepts int only
in the Example2. Is this a bug or expected?

by the way same thing happends on a 64bit system with a
value of 0x8000000000000000.

Regards,
Kenji Noguchi
 
H

half.italian

Hi

I'm using Python 2.4.4 on 32bit x86 Linux. I have a problem with printing
hex string for a value larger than 0x800000000 when the value is given to
% operator via an instance of a class with __int__(). If I pass a long value
to % operator it works just fine.

Example1 -- pass a long value directly. this works.>>> x=0x80000000

'80000000'

Example2 -- pass an instance of a class with __int__()>>> class X:

... def __init__(self, v):
... self.v = v
... def __int__(self):
... return self.v
...>>> y = X(0x80000000)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: int argument required



The behavior looks inconsistent. By the way __int__ actually
returned a long type value in the Example2. The "%08x" allows
either int or long in the Example1, however it accepts int only
in the Example2. Is this a bug or expected?

by the way same thing happends on a 64bit system with a
value of 0x8000000000000000.

Regards,
Kenji Noguchi

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,969
Members
47,524
Latest member
ecomwebdesign

Latest Threads

Top