Add VerNum.__index__() for Python 3 support

On Python 3, some functions like range() don't try to call the __int__()
method to cast an object to integer, but try instead the __index__()
method.

Add an __index__() method to mimick correctly the int type on Python 3.

Change-Id: I8df116d80e201778714a59367600eaef644266ed
This commit is contained in:
Victor Stinner 2015-07-28 12:55:39 +02:00
parent 8252703f56
commit 1384e901b0
2 changed files with 10 additions and 0 deletions

View File

@ -69,6 +69,13 @@ class TestVerNum(fixture.Base):
self.assertTrue(VerNum(2) >= 1)
self.assertFalse(VerNum(1) >= 2)
def test_int_cast(self):
ver = VerNum(3)
# test __int__
self.assertEqual(int(ver), 3)
# test __index__: range() doesn't call __int__
self.assertEqual(list(range(ver, ver)), [])
class TestVersion(fixture.Pathed):

View File

@ -65,6 +65,9 @@ class VerNum(object):
def __int__(self):
return int(self.value)
def __index__(self):
return int(self.value)
if six.PY3:
def __hash__(self):
return hash(self.value)