Skip to content

Commit

Permalink
'with' statement for PubSub (#765)
Browse files Browse the repository at this point in the history
PubSub objects are now context managers.
  • Loading branch information
Dmitry Kuragin authored and andymccurdy committed Dec 29, 2019
1 parent 8b76019 commit a41465e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
6 changes: 6 additions & 0 deletions redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3339,6 +3339,12 @@ def __init__(self, connection_pool, shard_hint=None,
]
self.reset()

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self.reset()

def __del__(self):
try:
# if this object went out of scope prior to shutting down
Expand Down
9 changes: 9 additions & 0 deletions tests/test_pubsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,15 @@ def test_pattern_message_handler(self, r):
new_data,
pattern=self.pattern)

def test_context_manager(self, r):
with r.pubsub() as pubsub:
pubsub.subscribe('foo')
assert pubsub.connection is not None

assert pubsub.connection is None
assert pubsub.channels == {}
assert pubsub.patterns == {}


class TestPubSubRedisDown(object):

Expand Down

0 comments on commit a41465e

Please sign in to comment.