Skip to content

Commit 1bd4f11

Browse files
Add Batch._reset_state for DRY. (#3169)
1 parent 6cca1ec commit 1bd4f11

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

pubsub/google/cloud/pubsub/topic.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -444,20 +444,19 @@ class Batch(object):
444444
def __init__(self, topic, client, max_interval=_INFINITY,
445445
max_messages=_INFINITY, max_size=1024 * 1024 * 9):
446446
self.topic = topic
447+
self.client = client
447448
self.messages = []
448449
self.message_ids = []
449-
self.client = client
450450

451451
# Set the autocommit rules. If the interval or number of messages
452452
# is exceeded, then the .publish() method will imply a commit.
453453
self._max_interval = max_interval
454454
self._max_messages = max_messages
455455
self._max_size = max_size
456456

457-
# Set the initial starting timestamp (used against the interval)
458-
# and initial size.
459-
self._start_timestamp = time.time()
460-
self._current_size = 0
457+
# Set up the initial state, initializing messages, the starting
458+
# timestamp, etc.
459+
self._reset_state()
461460

462461
def __enter__(self):
463462
return self
@@ -469,6 +468,13 @@ def __exit__(self, exc_type, exc_val, exc_tb):
469468
def __iter__(self):
470469
return iter(self.message_ids)
471470

471+
def _reset_state(self):
472+
"""Reset the state of this batch."""
473+
474+
del self.messages[:]
475+
self._start_timestamp = time.time()
476+
self._current_size = 0
477+
472478
def publish(self, message, **attrs):
473479
"""Emulate publishing a message, but save it.
474480
@@ -526,6 +532,4 @@ def commit(self, client=None):
526532
api = client.publisher_api
527533
message_ids = api.topic_publish(self.topic.full_name, self.messages[:])
528534
self.message_ids.extend(message_ids)
529-
del self.messages[:]
530-
self._start_timestamp = time.time()
531-
self._current_size = 0
535+
self._reset_state()

0 commit comments

Comments
 (0)