Don't rely on external package `first`.

This commit is contained in:
Vincent Driessen 2014-04-04 13:01:30 +02:00
parent a55be12864
commit 3649ff863b
3 changed files with 41 additions and 2 deletions

View File

@ -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):

View File

@ -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

View File

@ -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']