Is there any case where len(someObj) does not call someObj's __len__ function?

前端 未结 5 1493
挽巷
挽巷 2020-12-06 02:45

Is there any case where len(someObj) does not call someObj\'s __len__ function?

I recently replaced the former with the latter in a (sucess

5条回答
  •  没有蜡笔的小新
    2020-12-06 03:19

    There are cases where len(someObj) is not the same as someObj.__len__() since len() validates __len__()'s return value. Here are the possible errors in Python 3.6.9:

    • Too small, i.e. less than 0

      ValueError: __len__() should return >= 0
      
    • Too big, i.e. greater than sys.maxsize (CPython-specific, per the docs)

      OverflowError: cannot fit 'int' into an index-sized integer
      
    • An invalid type, e.g float

      TypeError: 'float' object cannot be interpreted as an integer
      
    • Missing, e.g. len(object)

      TypeError: object of type 'type' has no len()
      

      I mention this because object.__len__() raises a different exception, AttributeError.

    It's also worth noting that range(sys.maxsize+1) is valid, but its __len__() raises an exception:

    OverflowError: Python int too large to convert to C ssize_t
    

提交回复
热议问题