Skip to content

Commit c354dca

Browse files
committed
Add __len__ and __bool__ methods
It's useful to know how many pending commands are on a Pipeline object; this adds a __len__ method for that. A __bool__ method is added so Pipeline instances will evaluate to True even if they have no pending commands. (I added a __bool__ method to RedisObject also, since it has a __len__ method.)
1 parent 3f9693b commit c354dca

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

django/sierra/utils/redisobjs.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,18 @@ def __init__(self, conn=REDIS_CONNECTION):
148148
self.pipe = conn.pipeline()
149149
self.reset(False)
150150

151+
def __len__(self):
152+
"""
153+
Returns the number of currently pending cmds on the pipeline.
154+
"""
155+
return self.pipe.__len__()
156+
157+
def __bool__(self):
158+
# Since we have __len__ defined we need __bool__ too to
159+
# override cases where __len__ is 0 causing an instance to
160+
# evaluate as False.
161+
return True
162+
151163
def reset(self, reset_pipe=True):
152164
"""
153165
Resets this Pipeline object's state.
@@ -749,7 +761,7 @@ def get_all(self, obj):
749761
Implement this in each subclass.
750762
"""
751763
pass
752-
764+
753765
def save(self, obj, data, update, index, was_none=False):
754766
"""
755767
Returns a Pipeline with cmds to save a Redis object.
@@ -1324,6 +1336,12 @@ def __init__(self, entity, id_, pipe=None, defer=False):
13241336
def __len__(self):
13251337
return self.len
13261338

1339+
def __bool__(self):
1340+
# Since we have __len__ defined we need __bool__ too to
1341+
# override cases where __len__ is 0 causing an instance to
1342+
# evaluate as False.
1343+
return True
1344+
13271345
@property
13281346
def len(self):
13291347
"""

0 commit comments

Comments
 (0)