5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

__len__の戻り値に気を付ける

Posted at

自作のクラスに__len__をオーバーライドし、呼び出したところ、次のようなエラーが発生。

OverflowError: cannot fit 'int' into an index-sized integer

原因は__len__の仕様にありました。どうやら__len__の戻り値は以下の条件を満たす必要があるようです。

  • 整数型(int)
  • 0以上
  • 符号付32bit整数の上限(0x7FFFFFFF)以下
    • 「符号付32bit整数」の部分は環境によって違う可能性あり

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

わたしの場合は__len__の戻り値が大きすぎたせいで、例外になっていたようですね(´・ω・`)

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?