Don't rely on external package `first`.

main
Vincent Driessen 11 years ago
parent a55be12864
commit 3649ff863b

@ -4,9 +4,9 @@ from functools import partial
from warnings import warn from warnings import warn
import redis import redis
from first import first
from rq import use_connection from rq import use_connection
from rq.utils import first
def add_standard_arguments(parser): def add_standard_arguments(parser):

@ -181,3 +181,42 @@ def utcformat(dt):
def utcparse(string): def utcparse(string):
return datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%SZ") 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

@ -17,7 +17,7 @@ def get_version():
def get_dependencies(): def get_dependencies():
deps = ['redis >= 2.4.13', 'first >= 2.0'] deps = ['redis >= 2.4.13']
if sys.version_info < (2, 7) or \ if sys.version_info < (2, 7) or \
(sys.version_info >= (3, 0) and sys.version_info < (3, 1)): (sys.version_info >= (3, 0) and sys.version_info < (3, 1)):
deps += ['importlib'] deps += ['importlib']

Loading…
Cancel
Save