mirror of https://github.com/rq/rq.git
Don't rely on external package `first`.
This commit is contained in:
parent
a55be12864
commit
3649ff863b
|
@ -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):
|
||||
|
|
39
rq/utils.py
39
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
|
||||
|
|
Loading…
Reference in New Issue