Skip to content

Commit

Permalink
Pipelines now have a __len__() method.
Browse files Browse the repository at this point in the history
The length of a pipeline is defined as the length of its command
stack.  This makes it easy to inspect the number of batched commands
and to write conditional logic for empty pipelines.
  • Loading branch information
jparise committed Jan 7, 2013
1 parent 395ca0e commit 5827683
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
3 changes: 3 additions & 0 deletions redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1624,6 +1624,9 @@ def __del__(self):
except:
pass

def __len__(self):
return len(self.command_stack)

def reset(self):
self.command_stack = []
self.scripts = set()
Expand Down
16 changes: 16 additions & 0 deletions tests/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ def test_pipeline(self):
]
)

def test_pipeline_length(self):
with self.client.pipeline() as pipe:
# Initially empty.
self.assertEquals(len(pipe), 0)
self.assertFalse(pipe)

# Fill 'er up!
pipe.set('a', 'a1').set('b', 'b1').set('c', 'c1')
self.assertEquals(len(pipe), 3)
self.assertTrue(pipe)

# Execute calls reset(), so empty once again.
pipe.execute()
self.assertEquals(len(pipe), 0)
self.assertFalse(pipe)

def test_pipeline_no_transaction(self):
with self.client.pipeline(transaction=False) as pipe:
pipe.set('a', 'a1').set('b', 'b1').set('c', 'c1')
Expand Down

0 comments on commit 5827683

Please sign in to comment.