When I overridden __len__
in my class and called it, the following error occurred.
OverflowError: cannot fit 'int' into an index-sized integer
The cause was in the __len__
specification. Apparently, the return value of __len__
must meet the following conditions.
--Integer type (int)
--0 or more
--Below and below the upper limit of signed 32-bit integers (0x7FFFFFFF
)
--The "signed 32-bit integer" part may differ depending on the environment.
class ReturnStr(object):
def __len__(self): return "abc"
class ReturnFloat(object):
def __len__(self): return 1.0
class ReturnNegativeNumber(object):
def __len__(self): return -1
class ReturnBigNumber(object):
def __len__(self): return 0x7FFFFFFF + 1
class ReturnSmallNumber(object):
def __len__(self): return 0x7FFFFFFF
if __name__ == "__main__":
len(ReturnStr()) #=> TypeError: 'str' object cannot be interpreted as an integer
len(ReturnFloat()) #=> TypeError: 'float' object cannot be interpreted as an integer
len(ReturnNegativeNumber()) #=> ValueError: __len__() should return >= 0
len(ReturnBigNumber()) #=> OverflowError: cannot fit 'int' into an index-sized integer
len(ReturnSmallNumber()) #=> OK
In my case, it seems that it was an exception because the return value of __len__
was too large (´ ・ ω ・`)
Recommended Posts