Allow unpacking a Range object like a tuple

Define the __getitem__ method on Range. Allows:

- Unpacking ranges as a tuple
- Indexing the Range with 0 & 1 like a tuple
- Coercing to a tuple
- Iterating like a tuple
This commit is contained in:
Jon Dufresne 2018-07-24 17:20:59 -07:00
parent 0e89b9de2c
commit 5d8c22cf9d
2 changed files with 18 additions and 0 deletions

View File

@ -105,6 +105,10 @@ class Range(object):
return False
return self._bounds[1] == ']'
def __getitem__(self, key):
t = self._lower, self._upper
return t[key]
def __contains__(self, x):
if self._bounds is None:
return False

View File

@ -1386,6 +1386,20 @@ class RangeTestCase(unittest.TestCase):
r = Range(0, 4)
self.assertEqual(loads(dumps(r)), r)
def test_getitem(self):
from psycopg2.extras import Range
r = Range(0, 4)
self.assertEqual(tuple(r), (0, 4))
self.assertEqual(list(r), [0, 4])
lower, upper = r
self.assertEqual(lower, 0)
self.assertEqual(upper, 4)
self.assertEqual(r[0], 0)
self.assertEqual(r[1], 4)
# String indexes are not allowed.
with self.assertRaises(TypeError):
r['abc']
def skip_if_no_range(f):
@wraps(f)