Skip to content

Commit

Permalink
Merge pull request #20 from Revolution1/refactory/match-to-filter
Browse files Browse the repository at this point in the history
rename match to filter
  • Loading branch information
Revolution1 committed Mar 22, 2018
2 parents e0b6985 + 9dcd04c commit cce9269
Showing 1 changed file with 22 additions and 22 deletions.
44 changes: 22 additions & 22 deletions etcd3/stateful/watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,45 +133,45 @@ def request_create(self):
def request_cancel(self): # pragma: no cover
pass

def get_matcher(self, match):
if callable(match):
match_func = match
elif isinstance(match, (six.string_types, bytes)):
regex = re.compile(match)
def get_filter(self, filter):
if callable(filter):
filter_func = filter
elif isinstance(filter, (six.string_types, bytes)):
regex = re.compile(filter)

def match_func(e):
def filter_func(e):
key = e.key
if six.PY3:
try:
key = six.text_type(e.key, encoding='utf-8')
except Exception:
return
return regex.match(key)
elif match is None:
match_func = lambda e: True
elif isinstance(match, EventType):
match_func = lambda e: e.type == match
elif filter is None:
filter_func = lambda e: True
elif isinstance(filter, EventType):
filter_func = lambda e: e.type == filter
else:
raise TypeError('expect match to be one of string, EventType, callable got %s' % type(match))
return match_func
raise TypeError('expect filter to be one of string, EventType, callable got %s' % type(filter))
return filter_func

def onEvent(self, match_or_cb, cb=None):
def onEvent(self, filter_or_cb, cb=None):
if cb:
match = match_or_cb
filter = filter_or_cb
else:
match = None
cb = match_or_cb
filter = None
cb = filter_or_cb
if not callable(cb):
raise TypeError('callback should be a callable')
self.callbacks.append((self.get_matcher(match), match, cb))
self.callbacks.append((self.get_filter(filter), filter, cb))

def clear_callbacks(self):
self.callbacks = []

def dispatch_event(self, event):
log.debug("dispatching event '%s'" % event)
for match_func, match, cb in self.callbacks:
if match_func(event):
for filter, _, cb in self.callbacks:
if filter(event):
cb(event)

def _run(self):
Expand Down Expand Up @@ -241,14 +241,14 @@ def runDaemon(self):
t.setDaemon(True)
t.start()

def watch_once(self, match=None, timeout=None):
matcher = self.get_matcher(match)
def watch_once(self, filter=None, timeout=None):
filter = self.get_filter(filter)
old_timeout = self.timeout
self.timeout = timeout
try:
with self:
for event in self:
if matcher(event):
if filter(event):
self.stop()
return event
except (ConnectionError, ChunkedEncodingError): # timeout
Expand Down

0 comments on commit cce9269

Please sign in to comment.