From 3649ff863bc09e56a6947eb5a0b958af3b6f81df Mon Sep 17 00:00:00 2001 From: Vincent Driessen Date: Fri, 4 Apr 2014 13:01:30 +0200 Subject: [PATCH] Don't rely on external package `first`. --- rq/scripts/__init__.py | 2 +- rq/utils.py | 39 +++++++++++++++++++++++++++++++++++++++ setup.py | 2 +- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/rq/scripts/__init__.py b/rq/scripts/__init__.py index ec188ee5..bfbb3a13 100644 --- a/rq/scripts/__init__.py +++ b/rq/scripts/__init__.py @@ -4,9 +4,9 @@ from functools import partial from warnings import warn import redis -from first import first from rq import use_connection +from rq.utils import first def add_standard_arguments(parser): diff --git a/rq/utils.py b/rq/utils.py index f182210e..7fd1b1e2 100644 --- a/rq/utils.py +++ b/rq/utils.py @@ -181,3 +181,42 @@ def utcformat(dt): def utcparse(string): return datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%SZ") + + +def first(iterable, default=None, key=None): + """ + Return first element of `iterable` that evaluates true, else return None + (or an optional default value). + + >>> first([0, False, None, [], (), 42]) + 42 + + >>> first([0, False, None, [], ()]) is None + True + + >>> first([0, False, None, [], ()], default='ohai') + 'ohai' + + >>> import re + >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) + >>> m.group(1) + 'bc' + + The optional `key` argument specifies a one-argument predicate function + like that used for `filter()`. The `key` argument, if supplied, must be + in keyword form. For example: + + >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) + 4 + + """ + if key is None: + for el in iterable: + if el: + return el + else: + for el in iterable: + if key(el): + return el + + return default diff --git a/setup.py b/setup.py index 91ab9111..500093ac 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ def get_version(): def get_dependencies(): - deps = ['redis >= 2.4.13', 'first >= 2.0'] + deps = ['redis >= 2.4.13'] if sys.version_info < (2, 7) or \ (sys.version_info >= (3, 0) and sys.version_info < (3, 1)): deps += ['importlib']