Skip to content

Commit

Permalink
RangeSet: allow slice object in fromone()
Browse files Browse the repository at this point in the history
  • Loading branch information
Stephane Thiell committed Mar 14, 2012
1 parent dcfbdbb commit 332bdc4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/ClusterShell/RangeSet.py
Expand Up @@ -185,9 +185,16 @@ def fromlist(cls, rnglist, autostep=None):

@classmethod
def fromone(cls, index, pad=0, autostep=None):
"""Class method that returns a new RangeSet of one single item."""
"""Class method that returns a new RangeSet of one single item or
a single range (from integer or slice object)."""
inst = RangeSet(autostep=autostep)
inst.add(index, pad)
# support slice object with duck-typing
try:
inst.add(index, pad)
except TypeError:
if not index.stop:
raise ValueError("Invalid range upper limit (%s)" % index.stop)
inst.add_range(index.start or 0, index.stop, index.step or 1, pad)
return inst

def get_autostep(self):
Expand Down
16 changes: 16 additions & 0 deletions tests/RangeSetTest.py
Expand Up @@ -691,6 +691,22 @@ def testFromOneConstructor(self):
rgs = RangeSet.fromone(42)
self.assertEqual(str(rgs), "42")
self.assertEqual(len(rgs), 1)
# also support slice object (v1.6+)
rgs = RangeSet.fromone(slice(42))
self.assertEqual(str(rgs), "0-41")
self.assertEqual(len(rgs), 42)
self.assertRaises(ValueError, RangeSet.fromone, slice(12, None))
rgs = RangeSet.fromone(slice(42, 43))
self.assertEqual(str(rgs), "42")
self.assertEqual(len(rgs), 1)
rgs = RangeSet.fromone(slice(42, 48))
self.assertEqual(str(rgs), "42-47")
self.assertEqual(len(rgs), 6)
rgs = RangeSet.fromone(slice(42, 57, 2))
self.assertEqual(str(rgs), "42,44,46,48,50,52,54,56")
rgs.autostep = 3
self.assertEqual(str(rgs), "42-56/2")
self.assertEqual(len(rgs), 8)

def testIterator(self):
"""test RangeSet iterator"""
Expand Down

0 comments on commit 332bdc4

Please sign in to comment.