mirror of
https://github.com/psycopg/psycopg2.git
synced 2025-08-03 11:50:08 +03:00
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:
parent
0e89b9de2c
commit
5d8c22cf9d
|
@ -105,6 +105,10 @@ class Range(object):
|
||||||
return False
|
return False
|
||||||
return self._bounds[1] == ']'
|
return self._bounds[1] == ']'
|
||||||
|
|
||||||
|
def __getitem__(self, key):
|
||||||
|
t = self._lower, self._upper
|
||||||
|
return t[key]
|
||||||
|
|
||||||
def __contains__(self, x):
|
def __contains__(self, x):
|
||||||
if self._bounds is None:
|
if self._bounds is None:
|
||||||
return False
|
return False
|
||||||
|
|
|
@ -1386,6 +1386,20 @@ class RangeTestCase(unittest.TestCase):
|
||||||
r = Range(0, 4)
|
r = Range(0, 4)
|
||||||
self.assertEqual(loads(dumps(r)), r)
|
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):
|
def skip_if_no_range(f):
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user