nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/calc.py
_memory_decorator
(memory, key_func)
return decorator
51
79
def _memory_decorator(memory, key_func): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # We inline this here since @memoize also targets microoptimizations key = key_func(*args, **kwargs) if key_func else \ args + tuple(sorted(kwargs.items())) if kwargs else args try: return memory[key] except KeyError: try: value = memory[key] = func(*args, **kwargs) return value except SkipMemoization as e: return e.args[0] if e.args else None def invalidate(*args, **kwargs): key = key_func(*args, **kwargs) if key_func else \ args + tuple(sorted(kwargs.items())) if kwargs else args memory.pop(key, None) wrapper.invalidate = invalidate def invalidate_all(): memory.clear() wrapper.invalidate_all = invalidate_all wrapper.memory = memory return wrapper return decorator
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/calc.py#L51-L79
29
[ 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 ]
86.206897
[ 13, 14 ]
6.896552
false
94.285714
29
7
93.103448
0
def _memory_decorator(memory, key_func): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # We inline this here since @memoize also targets microoptimizations key = key_func(*args, **kwargs) if key_func else \ args + tuple(sorted(kwargs.items())) if kwargs else args try: return memory[key] except KeyError: try: value = memory[key] = func(*args, **kwargs) return value except SkipMemoization as e: return e.args[0] if e.args else None def invalidate(*args, **kwargs): key = key_func(*args, **kwargs) if key_func else \ args + tuple(sorted(kwargs.items())) if kwargs else args memory.pop(key, None) wrapper.invalidate = invalidate def invalidate_all(): memory.clear() wrapper.invalidate_all = invalidate_all wrapper.memory = memory return wrapper return decorator
20,061
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/calc.py
_make_lookuper
(silent)
return make_lookuper
111
148
def _make_lookuper(silent): def make_lookuper(func): """ Creates a single argument function looking up result in a memory. Decorated function is called once on first lookup and should return all available arg-value pairs. Resulting function will raise LookupError when using @make_lookuper or simply return None when using @silent_lookuper. """ has_args, has_keys = has_arg_types(func) assert not has_keys, \ 'Lookup table building function should not have keyword arguments' if has_args: @memoize def wrapper(*args): f = lambda: func(*args) f.__name__ = '%s(%s)' % (func.__name__, ', '.join(map(str, args))) return make_lookuper(f) else: memory = {} def wrapper(arg): if not memory: memory[object()] = None # prevent continuos memory refilling memory.update(func()) if silent: return memory.get(arg) elif arg in memory: return memory[arg] else: raise LookupError("Failed to look up %s(%s)" % (func.__name__, arg)) return wraps(func)(wrapper) return make_lookuper
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/calc.py#L111-L148
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37 ]
100
[]
0
true
94.285714
38
9
100
0
def _make_lookuper(silent): def make_lookuper(func): has_args, has_keys = has_arg_types(func) assert not has_keys, \ 'Lookup table building function should not have keyword arguments' if has_args: @memoize def wrapper(*args): f = lambda: func(*args) f.__name__ = '%s(%s)' % (func.__name__, ', '.join(map(str, args))) return make_lookuper(f) else: memory = {} def wrapper(arg): if not memory: memory[object()] = None # prevent continuos memory refilling memory.update(func()) if silent: return memory.get(arg) elif arg in memory: return memory[arg] else: raise LookupError("Failed to look up %s(%s)" % (func.__name__, arg)) return wraps(func)(wrapper) return make_lookuper
20,062
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/calc.py
CacheMemory.__init__
(self, timeout)
82
84
def __init__(self, timeout): self.timeout = timeout self.clear()
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/calc.py#L82-L84
29
[ 0, 1, 2 ]
100
[]
0
true
94.285714
3
1
100
0
def __init__(self, timeout): self.timeout = timeout self.clear()
20,063
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/calc.py
CacheMemory.__setitem__
(self, key, value)
86
90
def __setitem__(self, key, value): expires_at = time.time() + self.timeout dict.__setitem__(self, key, (value, expires_at)) self._keys.append(key) self._expires.append(expires_at)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/calc.py#L86-L90
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
94.285714
5
1
100
0
def __setitem__(self, key, value): expires_at = time.time() + self.timeout dict.__setitem__(self, key, (value, expires_at)) self._keys.append(key) self._expires.append(expires_at)
20,064
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/calc.py
CacheMemory.__getitem__
(self, key)
return value
92
97
def __getitem__(self, key): value, expires_at = dict.__getitem__(self, key) if expires_at <= time.time(): self.expire() raise KeyError(key) return value
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/calc.py#L92-L97
29
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
94.285714
6
2
100
0
def __getitem__(self, key): value, expires_at = dict.__getitem__(self, key) if expires_at <= time.time(): self.expire() raise KeyError(key) return value
20,065
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/calc.py
CacheMemory.expire
(self)
99
103
def expire(self): i = bisect(self._expires, time.time()) for _ in range(i): self._expires.popleft() self.pop(self._keys.popleft(), None)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/calc.py#L99-L103
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
94.285714
5
2
100
0
def expire(self): i = bisect(self._expires, time.time()) for _ in range(i): self._expires.popleft() self.pop(self._keys.popleft(), None)
20,066
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/calc.py
CacheMemory.clear
(self)
105
108
def clear(self): dict.clear(self) self._keys = deque() self._expires = deque()
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/calc.py#L105-L108
29
[ 0, 1, 2, 3 ]
100
[]
0
true
94.285714
4
1
100
0
def clear(self): dict.clear(self) self._keys = deque() self._expires = deque()
20,067
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
identity
(x)
return x
Returns its argument.
Returns its argument.
16
18
def identity(x): """Returns its argument.""" return x
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L16-L18
29
[ 0, 1, 2 ]
100
[]
0
true
98.611111
3
1
100
1
def identity(x): return x
20,068
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
constantly
(x)
return lambda *a, **kw: x
Creates a function accepting any args, but always returning x.
Creates a function accepting any args, but always returning x.
20
22
def constantly(x): """Creates a function accepting any args, but always returning x.""" return lambda *a, **kw: x
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L20-L22
29
[ 0, 1, 2 ]
100
[]
0
true
98.611111
3
1
100
1
def constantly(x): return lambda *a, **kw: x
20,069
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
caller
(*a, **kw)
return lambda f: f(*a, **kw)
Creates a function calling its sole argument with given *a, **kw.
Creates a function calling its sole argument with given *a, **kw.
25
27
def caller(*a, **kw): """Creates a function calling its sole argument with given *a, **kw.""" return lambda f: f(*a, **kw)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L25-L27
29
[ 0, 1, 2 ]
100
[]
0
true
98.611111
3
1
100
1
def caller(*a, **kw): return lambda f: f(*a, **kw)
20,070
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
func_partial
(func, *args, **kwargs)
return lambda *a, **kw: func(*(args + a), **dict(kwargs, **kw))
A functools.partial alternative, which returns a real function. Can be used to construct methods.
A functools.partial alternative, which returns a real function. Can be used to construct methods.
29
32
def func_partial(func, *args, **kwargs): """A functools.partial alternative, which returns a real function. Can be used to construct methods.""" return lambda *a, **kw: func(*(args + a), **dict(kwargs, **kw))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L29-L32
29
[ 0, 1, 2, 3 ]
100
[]
0
true
98.611111
4
1
100
2
def func_partial(func, *args, **kwargs): return lambda *a, **kw: func(*(args + a), **dict(kwargs, **kw))
20,071
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
rpartial
(func, *args, **kwargs)
return lambda *a, **kw: func(*(a + args), **dict(kwargs, **kw))
Partially applies last arguments. New keyworded arguments extend and override kwargs.
Partially applies last arguments. New keyworded arguments extend and override kwargs.
34
37
def rpartial(func, *args, **kwargs): """Partially applies last arguments. New keyworded arguments extend and override kwargs.""" return lambda *a, **kw: func(*(a + args), **dict(kwargs, **kw))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L34-L37
29
[ 0, 1, 2, 3 ]
100
[]
0
true
98.611111
4
1
100
2
def rpartial(func, *args, **kwargs): return lambda *a, **kw: func(*(a + args), **dict(kwargs, **kw))
20,072
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
curry
(func, n=EMPTY)
Curries func into a chain of one argument functions.
Curries func into a chain of one argument functions.
40
50
def curry(func, n=EMPTY): """Curries func into a chain of one argument functions.""" if n is EMPTY: n = get_spec(func).max_n if n <= 1: return func elif n == 2: return lambda x: lambda y: func(x, y) else: return lambda x: curry(partial(func, x), n - 1)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L40-L50
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
98.611111
11
4
100
1
def curry(func, n=EMPTY): if n is EMPTY: n = get_spec(func).max_n if n <= 1: return func elif n == 2: return lambda x: lambda y: func(x, y) else: return lambda x: curry(partial(func, x), n - 1)
20,073
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
rcurry
(func, n=EMPTY)
Curries func into a chain of one argument functions. Arguments are passed from right to left.
Curries func into a chain of one argument functions. Arguments are passed from right to left.
53
64
def rcurry(func, n=EMPTY): """Curries func into a chain of one argument functions. Arguments are passed from right to left.""" if n is EMPTY: n = get_spec(func).max_n if n <= 1: return func elif n == 2: return lambda x: lambda y: func(y, x) else: return lambda x: rcurry(rpartial(func, x), n - 1)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L53-L64
29
[ 0, 1, 2, 3, 4, 5, 6, 8, 9, 11 ]
83.333333
[ 7 ]
8.333333
false
98.611111
12
4
91.666667
2
def rcurry(func, n=EMPTY): if n is EMPTY: n = get_spec(func).max_n if n <= 1: return func elif n == 2: return lambda x: lambda y: func(y, x) else: return lambda x: rcurry(rpartial(func, x), n - 1)
20,074
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
autocurry
(func, n=EMPTY, _spec=None, _args=(), _kwargs={})
return autocurried
Creates a version of func returning its partial applications until sufficient arguments are passed.
Creates a version of func returning its partial applications until sufficient arguments are passed.
68
91
def autocurry(func, n=EMPTY, _spec=None, _args=(), _kwargs={}): """Creates a version of func returning its partial applications until sufficient arguments are passed.""" spec = _spec or (get_spec(func) if n is EMPTY else Spec(n, set(), n, set(), False)) @wraps(func) def autocurried(*a, **kw): args = _args + a kwargs = _kwargs.copy() kwargs.update(kw) if not spec.kw and len(args) + len(kwargs) >= spec.max_n: return func(*args, **kwargs) elif len(args) + len(set(kwargs) & spec.names) >= spec.max_n: return func(*args, **kwargs) elif len(args) + len(set(kwargs) & spec.req_names) >= spec.req_n: try: return func(*args, **kwargs) except TypeError: return autocurry(func, _spec=spec, _args=args, _kwargs=kwargs) else: return autocurry(func, _spec=spec, _args=args, _kwargs=kwargs) return autocurried
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L68-L91
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23 ]
95.833333
[]
0
false
98.611111
24
8
100
2
def autocurry(func, n=EMPTY, _spec=None, _args=(), _kwargs={}): spec = _spec or (get_spec(func) if n is EMPTY else Spec(n, set(), n, set(), False)) @wraps(func) def autocurried(*a, **kw): args = _args + a kwargs = _kwargs.copy() kwargs.update(kw) if not spec.kw and len(args) + len(kwargs) >= spec.max_n: return func(*args, **kwargs) elif len(args) + len(set(kwargs) & spec.names) >= spec.max_n: return func(*args, **kwargs) elif len(args) + len(set(kwargs) & spec.req_names) >= spec.req_n: try: return func(*args, **kwargs) except TypeError: return autocurry(func, _spec=spec, _args=args, _kwargs=kwargs) else: return autocurry(func, _spec=spec, _args=args, _kwargs=kwargs) return autocurried
20,075
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
iffy
(pred, action=EMPTY, default=identity)
Creates a function, which conditionally applies action or default.
Creates a function, which conditionally applies action or default.
94
103
def iffy(pred, action=EMPTY, default=identity): """Creates a function, which conditionally applies action or default.""" if action is EMPTY: return iffy(bool, pred, default) else: pred = make_pred(pred) action = make_func(action) return lambda v: action(v) if pred(v) else \ default(v) if callable(default) else \ default
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L94-L103
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
98.611111
10
2
100
1
def iffy(pred, action=EMPTY, default=identity): if action is EMPTY: return iffy(bool, pred, default) else: pred = make_pred(pred) action = make_func(action) return lambda v: action(v) if pred(v) else \ default(v) if callable(default) else \ default
20,076
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
compose
(*fs)
Composes passed functions.
Composes passed functions.
106
112
def compose(*fs): """Composes passed functions.""" if fs: pair = lambda f, g: lambda *a, **kw: f(g(*a, **kw)) return reduce(pair, map(make_func, fs)) else: return identity
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L106-L112
29
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
98.611111
7
2
100
1
def compose(*fs): if fs: pair = lambda f, g: lambda *a, **kw: f(g(*a, **kw)) return reduce(pair, map(make_func, fs)) else: return identity
20,077
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
rcompose
(*fs)
return compose(*reversed(fs))
Composes functions, calling them from left to right.
Composes functions, calling them from left to right.
114
116
def rcompose(*fs): """Composes functions, calling them from left to right.""" return compose(*reversed(fs))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L114-L116
29
[ 0, 1, 2 ]
100
[]
0
true
98.611111
3
1
100
1
def rcompose(*fs): return compose(*reversed(fs))
20,078
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
complement
(pred)
return compose(__not__, pred)
Constructs a complementary predicate.
Constructs a complementary predicate.
118
120
def complement(pred): """Constructs a complementary predicate.""" return compose(__not__, pred)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L118-L120
29
[ 0, 1, 2 ]
100
[]
0
true
98.611111
3
1
100
1
def complement(pred): return compose(__not__, pred)
20,079
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
ljuxt
(*fs)
return lambda *a, **kw: [f(*a, **kw) for f in extended_fs]
Constructs a juxtaposition of the given functions. Result returns a list of results of fs.
Constructs a juxtaposition of the given functions. Result returns a list of results of fs.
126
130
def ljuxt(*fs): """Constructs a juxtaposition of the given functions. Result returns a list of results of fs.""" extended_fs = list(map(make_func, fs)) return lambda *a, **kw: [f(*a, **kw) for f in extended_fs]
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L126-L130
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
98.611111
5
2
100
2
def ljuxt(*fs): extended_fs = list(map(make_func, fs)) return lambda *a, **kw: [f(*a, **kw) for f in extended_fs]
20,080
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcs.py
juxt
(*fs)
return lambda *a, **kw: (f(*a, **kw) for f in extended_fs)
Constructs a lazy juxtaposition of the given functions. Result returns an iterator of results of fs.
Constructs a lazy juxtaposition of the given functions. Result returns an iterator of results of fs.
132
136
def juxt(*fs): """Constructs a lazy juxtaposition of the given functions. Result returns an iterator of results of fs.""" extended_fs = list(map(make_func, fs)) return lambda *a, **kw: (f(*a, **kw) for f in extended_fs)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcs.py#L132-L136
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
98.611111
5
1
100
2
def juxt(*fs): extended_fs = list(map(make_func, fs)) return lambda *a, **kw: (f(*a, **kw) for f in extended_fs)
20,081
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
raiser
(exception_or_class=Exception, *args, **kwargs)
return _raiser
Constructs function that raises the given exception with given arguments on any invocation.
Constructs function that raises the given exception with given arguments on any invocation.
18
29
def raiser(exception_or_class=Exception, *args, **kwargs): """Constructs function that raises the given exception with given arguments on any invocation.""" if isinstance(exception_or_class, str): exception_or_class = Exception(exception_or_class) def _raiser(*a, **kw): if args or kwargs: raise exception_or_class(*args, **kwargs) else: raise exception_or_class return _raiser
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L18-L29
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 ]
91.666667
[]
0
false
86.538462
12
5
100
2
def raiser(exception_or_class=Exception, *args, **kwargs): if isinstance(exception_or_class, str): exception_or_class = Exception(exception_or_class) def _raiser(*a, **kw): if args or kwargs: raise exception_or_class(*args, **kwargs) else: raise exception_or_class return _raiser
20,082
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
ignore
(errors, default=None)
return decorator
Alters function to ignore given errors, returning default instead.
Alters function to ignore given errors, returning default instead.
34
46
def ignore(errors, default=None): """Alters function to ignore given errors, returning default instead.""" errors = _ensure_exceptable(errors) def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except errors: return default return wrapper return decorator
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L34-L46
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
86.538462
13
4
100
1
def ignore(errors, default=None): errors = _ensure_exceptable(errors) def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except errors: return default return wrapper return decorator
20,083
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
silent
(func)
return ignore(Exception)(func)
Alters function to ignore all exceptions.
Alters function to ignore all exceptions.
48
50
def silent(func): """Alters function to ignore all exceptions.""" return ignore(Exception)(func)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L48-L50
29
[ 0, 1, 2 ]
100
[]
0
true
86.538462
3
1
100
1
def silent(func): return ignore(Exception)(func)
20,084
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
reraise
(errors, into)
Reraises errors as other exception.
Reraises errors as other exception.
108
116
def reraise(errors, into): """Reraises errors as other exception.""" errors = _ensure_exceptable(errors) try: yield except errors as e: if callable(into) and not _is_exception_type(into): into = into(e) raise_from(into, e)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L108-L116
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
86.538462
9
4
100
1
def reraise(errors, into): errors = _ensure_exceptable(errors) try: yield except errors as e: if callable(into) and not _is_exception_type(into): into = into(e) raise_from(into, e)
20,085
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
retry
(call, tries, errors=Exception, timeout=0, filter_errors=None)
Makes decorated function retry up to tries times. Retries only on specified errors. Sleeps timeout or timeout(attempt) seconds between tries.
Makes decorated function retry up to tries times. Retries only on specified errors. Sleeps timeout or timeout(attempt) seconds between tries.
120
138
def retry(call, tries, errors=Exception, timeout=0, filter_errors=None): """Makes decorated function retry up to tries times. Retries only on specified errors. Sleeps timeout or timeout(attempt) seconds between tries.""" errors = _ensure_exceptable(errors) for attempt in range(tries): try: return call() except errors as e: if not (filter_errors is None or filter_errors(e)): raise # Reraise error on last attempt if attempt + 1 == tries: raise else: timeout_value = timeout(attempt) if callable(timeout) else timeout if timeout_value > 0: time.sleep(timeout_value)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L120-L138
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18 ]
94.736842
[]
0
false
86.538462
19
7
100
3
def retry(call, tries, errors=Exception, timeout=0, filter_errors=None): errors = _ensure_exceptable(errors) for attempt in range(tries): try: return call() except errors as e: if not (filter_errors is None or filter_errors(e)): raise # Reraise error on last attempt if attempt + 1 == tries: raise else: timeout_value = timeout(attempt) if callable(timeout) else timeout if timeout_value > 0: time.sleep(timeout_value)
20,086
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
fallback
(*approaches)
Tries several approaches until one works. Each approach has a form of (callable, expected_errors).
Tries several approaches until one works. Each approach has a form of (callable, expected_errors).
141
150
def fallback(*approaches): """Tries several approaches until one works. Each approach has a form of (callable, expected_errors).""" for approach in approaches: func, catch = (approach, Exception) if callable(approach) else approach catch = _ensure_exceptable(catch) try: return func() except catch: pass
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L141-L150
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
86.538462
10
3
100
2
def fallback(*approaches): for approach in approaches: func, catch = (approach, Exception) if callable(approach) else approach catch = _ensure_exceptable(catch) try: return func() except catch: pass
20,087
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
_ensure_exceptable
(errors)
return errors if _is_exception_type(errors) else tuple(errors)
Ensures that errors are passable to except clause. I.e. should be BaseException subclass or a tuple.
Ensures that errors are passable to except clause. I.e. should be BaseException subclass or a tuple.
152
155
def _ensure_exceptable(errors): """Ensures that errors are passable to except clause. I.e. should be BaseException subclass or a tuple.""" return errors if _is_exception_type(errors) else tuple(errors)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L152-L155
29
[ 0, 1, 2, 3 ]
100
[]
0
true
86.538462
4
1
100
2
def _ensure_exceptable(errors): return errors if _is_exception_type(errors) else tuple(errors)
20,088
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
_is_exception_type
(value)
return isinstance(value, type) and issubclass(value, BaseException)
158
159
def _is_exception_type(value): return isinstance(value, type) and issubclass(value, BaseException)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L158-L159
29
[ 0, 1 ]
100
[]
0
true
86.538462
2
2
100
0
def _is_exception_type(value): return isinstance(value, type) and issubclass(value, BaseException)
20,089
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
limit_error_rate
(fails, timeout, exception=ErrorRateExceeded)
return decorator
If function fails to complete fails times in a row, calls to it will be intercepted for timeout with exception raised instead.
If function fails to complete fails times in a row, calls to it will be intercepted for timeout with exception raised instead.
165
194
def limit_error_rate(fails, timeout, exception=ErrorRateExceeded): """If function fails to complete fails times in a row, calls to it will be intercepted for timeout with exception raised instead.""" if isinstance(timeout, int): timeout = timedelta(seconds=timeout) def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if wrapper.blocked: if datetime.now() - wrapper.blocked < timeout: raise exception else: wrapper.blocked = None try: result = func(*args, **kwargs) except: # noqa wrapper.fails += 1 if wrapper.fails >= fails: wrapper.blocked = datetime.now() raise else: wrapper.fails = 0 return result wrapper.fails = 0 wrapper.blocked = None return wrapper return decorator
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L165-L194
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 25, 26, 27, 28, 29 ]
83.333333
[ 13, 23, 24 ]
10
false
86.538462
30
8
90
2
def limit_error_rate(fails, timeout, exception=ErrorRateExceeded): if isinstance(timeout, int): timeout = timedelta(seconds=timeout) def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if wrapper.blocked: if datetime.now() - wrapper.blocked < timeout: raise exception else: wrapper.blocked = None try: result = func(*args, **kwargs) except: # noqa wrapper.fails += 1 if wrapper.fails >= fails: wrapper.blocked = datetime.now() raise else: wrapper.fails = 0 return result wrapper.fails = 0 wrapper.blocked = None return wrapper return decorator
20,090
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
throttle
(period)
return decorator
Allows only one run in a period, the rest is skipped
Allows only one run in a period, the rest is skipped
197
216
def throttle(period): """Allows only one run in a period, the rest is skipped""" if isinstance(period, timedelta): period = period.total_seconds() def decorator(func): @wraps(func) def wrapper(*args, **kwargs): now = time.time() if wrapper.blocked_until and wrapper.blocked_until > now: return wrapper.blocked_until = now + period return func(*args, **kwargs) wrapper.blocked_until = None return wrapper return decorator
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L197-L216
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
86.538462
20
6
100
1
def throttle(period): if isinstance(period, timedelta): period = period.total_seconds() def decorator(func): @wraps(func) def wrapper(*args, **kwargs): now = time.time() if wrapper.blocked_until and wrapper.blocked_until > now: return wrapper.blocked_until = now + period return func(*args, **kwargs) wrapper.blocked_until = None return wrapper return decorator
20,091
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
post_processing
(call, func)
return func(call())
Post processes decorated function result with func.
Post processes decorated function result with func.
222
224
def post_processing(call, func): """Post processes decorated function result with func.""" return func(call())
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L222-L224
29
[ 0, 1, 2 ]
100
[]
0
true
86.538462
3
1
100
1
def post_processing(call, func): return func(call())
20,092
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
joining
(call, sep)
return sep.join(map(sep.__class__, call()))
Joins decorated function results with sep.
Joins decorated function results with sep.
231
233
def joining(call, sep): """Joins decorated function results with sep.""" return sep.join(map(sep.__class__, call()))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L231-L233
29
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
86.538462
3
1
66.666667
1
def joining(call, sep): return sep.join(map(sep.__class__, call()))
20,093
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
once_per
(*argnames)
return once
Call function only once for every combination of the given arguments.
Call function only once for every combination of the given arguments.
238
260
def once_per(*argnames): """Call function only once for every combination of the given arguments.""" def once(func): lock = threading.Lock() done_set = set() done_list = list() get_arg = arggetter(func) @wraps(func) def wrapper(*args, **kwargs): with lock: values = tuple(get_arg(name, args, kwargs) for name in argnames) if isinstance(values, Hashable): done, add = done_set, done_set.add else: done, add = done_list, done_list.append if values not in done: add(values) return func(*args, **kwargs) return wrapper return once
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L238-L260
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22 ]
95.652174
[ 16 ]
4.347826
false
86.538462
23
6
95.652174
1
def once_per(*argnames): def once(func): lock = threading.Lock() done_set = set() done_list = list() get_arg = arggetter(func) @wraps(func) def wrapper(*args, **kwargs): with lock: values = tuple(get_arg(name, args, kwargs) for name in argnames) if isinstance(values, Hashable): done, add = done_set, done_set.add else: done, add = done_list, done_list.append if values not in done: add(values) return func(*args, **kwargs) return wrapper return once
20,094
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
once_per_args
(func)
return once_per(*get_argnames(func))(func)
Call function once for every combination of values of its arguments.
Call function once for every combination of values of its arguments.
265
267
def once_per_args(func): """Call function once for every combination of values of its arguments.""" return once_per(*get_argnames(func))(func)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L265-L267
29
[ 0, 1, 2 ]
100
[]
0
true
86.538462
3
1
100
1
def once_per_args(func): return once_per(*get_argnames(func))(func)
20,095
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/flow.py
wrap_with
(call, ctx)
Turn context manager into a decorator
Turn context manager into a decorator
271
274
def wrap_with(call, ctx): """Turn context manager into a decorator""" with ctx: return call()
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/flow.py#L271-L274
29
[ 0, 1, 2, 3 ]
100
[]
0
true
86.538462
4
2
100
1
def wrap_with(call, ctx): with ctx: return call()
20,096
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/types.py
isa
(*types)
return lambda x: isinstance(x, types)
Creates a function checking if its argument is of any of given types.
Creates a function checking if its argument is of any of given types.
9
14
def isa(*types): """ Creates a function checking if its argument is of any of given types. """ return lambda x: isinstance(x, types)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/types.py#L9-L14
29
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
100
6
1
100
2
def isa(*types): return lambda x: isinstance(x, types)
20,097
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcolls.py
all_fn
(*fs)
return compose(all, juxt(*fs))
Constructs a predicate, which holds when all fs hold.
Constructs a predicate, which holds when all fs hold.
8
10
def all_fn(*fs): """Constructs a predicate, which holds when all fs hold.""" return compose(all, juxt(*fs))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcolls.py#L8-L10
29
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
1
def all_fn(*fs): return compose(all, juxt(*fs))
20,098
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcolls.py
any_fn
(*fs)
return compose(any, juxt(*fs))
Constructs a predicate, which holds when any fs holds.
Constructs a predicate, which holds when any fs holds.
12
14
def any_fn(*fs): """Constructs a predicate, which holds when any fs holds.""" return compose(any, juxt(*fs))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcolls.py#L12-L14
29
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
1
def any_fn(*fs): return compose(any, juxt(*fs))
20,099
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcolls.py
none_fn
(*fs)
return compose(none, juxt(*fs))
Constructs a predicate, which holds when none of fs hold.
Constructs a predicate, which holds when none of fs hold.
16
18
def none_fn(*fs): """Constructs a predicate, which holds when none of fs hold.""" return compose(none, juxt(*fs))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcolls.py#L16-L18
29
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
1
def none_fn(*fs): return compose(none, juxt(*fs))
20,100
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcolls.py
one_fn
(*fs)
return compose(one, juxt(*fs))
Constructs a predicate, which holds when exactly one of fs holds.
Constructs a predicate, which holds when exactly one of fs holds.
20
22
def one_fn(*fs): """Constructs a predicate, which holds when exactly one of fs holds.""" return compose(one, juxt(*fs))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcolls.py#L20-L22
29
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
1
def one_fn(*fs): return compose(one, juxt(*fs))
20,101
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/funcolls.py
some_fn
(*fs)
return compose(some, juxt(*fs))
Constructs a function, which calls fs one by one and returns first truthy result.
Constructs a function, which calls fs one by one and returns first truthy result.
24
27
def some_fn(*fs): """Constructs a function, which calls fs one by one and returns first truthy result.""" return compose(some, juxt(*fs))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/funcolls.py#L24-L27
29
[ 0, 1, 2, 3 ]
100
[]
0
true
100
4
1
100
2
def some_fn(*fs): return compose(some, juxt(*fs))
20,102
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
_factory
(coll, mapper=None)
34
48
def _factory(coll, mapper=None): coll_type = type(coll) # Hack for defaultdicts overridden constructor if isinstance(coll, defaultdict): item_factory = compose(mapper, coll.default_factory) if mapper and coll.default_factory \ else coll.default_factory return partial(defaultdict, item_factory) elif isinstance(coll, Iterator): return iter elif isinstance(coll, basestring): return coll_type().join elif coll_type in FACTORY_REPLACE: return FACTORY_REPLACE[coll_type] else: return coll_type
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L34-L48
29
[ 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14 ]
86.666667
[]
0
false
97.641509
15
6
100
0
def _factory(coll, mapper=None): coll_type = type(coll) # Hack for defaultdicts overridden constructor if isinstance(coll, defaultdict): item_factory = compose(mapper, coll.default_factory) if mapper and coll.default_factory \ else coll.default_factory return partial(defaultdict, item_factory) elif isinstance(coll, Iterator): return iter elif isinstance(coll, basestring): return coll_type().join elif coll_type in FACTORY_REPLACE: return FACTORY_REPLACE[coll_type] else: return coll_type
20,103
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
empty
(coll)
return _factory(coll)()
Creates an empty collection of the same type.
Creates an empty collection of the same type.
50
54
def empty(coll): """Creates an empty collection of the same type.""" if isinstance(coll, Iterator): return iter([]) return _factory(coll)()
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L50-L54
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.641509
5
2
100
1
def empty(coll): if isinstance(coll, Iterator): return iter([]) return _factory(coll)()
20,104
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
join
(colls)
Joins several collections of same type into one.
Joins several collections of same type into one.
73
99
def join(colls): """Joins several collections of same type into one.""" colls, colls_copy = tee(colls) it = iter(colls_copy) try: dest = next(it) except StopIteration: return None cls = dest.__class__ if isinstance(dest, basestring): return ''.join(colls) elif isinstance(dest, Mapping): result = dest.copy() for d in it: result.update(d) return result elif isinstance(dest, Set): return dest.union(*it) elif isinstance(dest, (Iterator, range)): return chain.from_iterable(colls) elif isinstance(dest, Iterable): # NOTE: this could be reduce(concat, ...), # more effective for low count return cls(chain.from_iterable(colls)) else: raise TypeError("Don't know how to join %s" % cls.__name__)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L73-L99
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]
100
[]
0
true
97.641509
27
8
100
1
def join(colls): colls, colls_copy = tee(colls) it = iter(colls_copy) try: dest = next(it) except StopIteration: return None cls = dest.__class__ if isinstance(dest, basestring): return ''.join(colls) elif isinstance(dest, Mapping): result = dest.copy() for d in it: result.update(d) return result elif isinstance(dest, Set): return dest.union(*it) elif isinstance(dest, (Iterator, range)): return chain.from_iterable(colls) elif isinstance(dest, Iterable): # NOTE: this could be reduce(concat, ...), # more effective for low count return cls(chain.from_iterable(colls)) else: raise TypeError("Don't know how to join %s" % cls.__name__)
20,105
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
merge
(*colls)
return join(colls)
Merges several collections of same type into one. Works with dicts, sets, lists, tuples, iterators and strings. For dicts later values take precedence.
Merges several collections of same type into one.
101
106
def merge(*colls): """Merges several collections of same type into one. Works with dicts, sets, lists, tuples, iterators and strings. For dicts later values take precedence.""" return join(colls)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L101-L106
29
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
97.641509
6
1
100
4
def merge(*colls): return join(colls)
20,106
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
join_with
(f, dicts, strict=False)
return lists
Joins several dicts, combining values with given function.
Joins several dicts, combining values with given function.
109
130
def join_with(f, dicts, strict=False): """Joins several dicts, combining values with given function.""" dicts = list(dicts) if not dicts: return {} elif not strict and len(dicts) == 1: return dicts[0] lists = {} for c in dicts: for k, v in iteritems(c): if k in lists: lists[k].append(v) else: lists[k] = [v] if f is not list: # kind of walk_values() inplace for k, v in iteritems(lists): lists[k] = f(v) return lists
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L109-L130
29
[ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
95.454545
[ 4 ]
4.545455
false
97.641509
22
9
95.454545
1
def join_with(f, dicts, strict=False): dicts = list(dicts) if not dicts: return {} elif not strict and len(dicts) == 1: return dicts[0] lists = {} for c in dicts: for k, v in iteritems(c): if k in lists: lists[k].append(v) else: lists[k] = [v] if f is not list: # kind of walk_values() inplace for k, v in iteritems(lists): lists[k] = f(v) return lists
20,107
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
merge_with
(f, *dicts)
return join_with(f, dicts)
Merges several dicts, combining values with given function.
Merges several dicts, combining values with given function.
132
134
def merge_with(f, *dicts): """Merges several dicts, combining values with given function.""" return join_with(f, dicts)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L132-L134
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def merge_with(f, *dicts): return join_with(f, dicts)
20,108
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
walk
(f, coll)
return _factory(coll)(xmap(f, iteritems(coll)))
Walks the collection transforming its elements with f. Same as map, but preserves coll type.
Walks the collection transforming its elements with f. Same as map, but preserves coll type.
137
140
def walk(f, coll): """Walks the collection transforming its elements with f. Same as map, but preserves coll type.""" return _factory(coll)(xmap(f, iteritems(coll)))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L137-L140
29
[ 0, 1, 2, 3 ]
100
[]
0
true
97.641509
4
1
100
2
def walk(f, coll): return _factory(coll)(xmap(f, iteritems(coll)))
20,109
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
walk_keys
(f, coll)
return walk(pair_f, coll)
Walks keys of the collection, mapping them with f.
Walks keys of the collection, mapping them with f.
142
150
def walk_keys(f, coll): """Walks keys of the collection, mapping them with f.""" f = make_func(f) # NOTE: we use this awkward construct instead of lambda to be Python 3 compatible def pair_f(pair): k, v = pair return f(k), v return walk(pair_f, coll)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L142-L150
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
97.641509
9
2
100
1
def walk_keys(f, coll): f = make_func(f) # NOTE: we use this awkward construct instead of lambda to be Python 3 compatible def pair_f(pair): k, v = pair return f(k), v return walk(pair_f, coll)
20,110
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
walk_values
(f, coll)
return _factory(coll, mapper=f)(xmap(pair_f, iteritems(coll)))
Walks values of the collection, mapping them with f.
Walks values of the collection, mapping them with f.
152
160
def walk_values(f, coll): """Walks values of the collection, mapping them with f.""" f = make_func(f) # NOTE: we use this awkward construct instead of lambda to be Python 3 compatible def pair_f(pair): k, v = pair return k, f(v) return _factory(coll, mapper=f)(xmap(pair_f, iteritems(coll)))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L152-L160
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
97.641509
9
2
100
1
def walk_values(f, coll): f = make_func(f) # NOTE: we use this awkward construct instead of lambda to be Python 3 compatible def pair_f(pair): k, v = pair return k, f(v) return _factory(coll, mapper=f)(xmap(pair_f, iteritems(coll)))
20,111
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
select
(pred, coll)
return _factory(coll)(xfilter(pred, iteritems(coll)))
Same as filter but preserves coll type.
Same as filter but preserves coll type.
164
166
def select(pred, coll): """Same as filter but preserves coll type.""" return _factory(coll)(xfilter(pred, iteritems(coll)))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L164-L166
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def select(pred, coll): return _factory(coll)(xfilter(pred, iteritems(coll)))
20,112
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
select_keys
(pred, coll)
return select(lambda pair: pred(pair[0]), coll)
Select part of the collection with keys passing pred.
Select part of the collection with keys passing pred.
168
171
def select_keys(pred, coll): """Select part of the collection with keys passing pred.""" pred = make_pred(pred) return select(lambda pair: pred(pair[0]), coll)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L168-L171
29
[ 0, 1, 2, 3 ]
100
[]
0
true
97.641509
4
1
100
1
def select_keys(pred, coll): pred = make_pred(pred) return select(lambda pair: pred(pair[0]), coll)
20,113
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
select_values
(pred, coll)
return select(lambda pair: pred(pair[1]), coll)
Select part of the collection with values passing pred.
Select part of the collection with values passing pred.
173
176
def select_values(pred, coll): """Select part of the collection with values passing pred.""" pred = make_pred(pred) return select(lambda pair: pred(pair[1]), coll)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L173-L176
29
[ 0, 1, 2, 3 ]
100
[]
0
true
97.641509
4
1
100
1
def select_values(pred, coll): pred = make_pred(pred) return select(lambda pair: pred(pair[1]), coll)
20,114
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
compact
(coll)
Removes falsy values from the collection.
Removes falsy values from the collection.
179
184
def compact(coll): """Removes falsy values from the collection.""" if isinstance(coll, Mapping): return select_values(bool, coll) else: return select(bool, coll)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L179-L184
29
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
97.641509
6
2
100
1
def compact(coll): if isinstance(coll, Mapping): return select_values(bool, coll) else: return select(bool, coll)
20,115
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
is_distinct
(coll, key=EMPTY)
Checks if all elements in the collection are different.
Checks if all elements in the collection are different.
189
194
def is_distinct(coll, key=EMPTY): """Checks if all elements in the collection are different.""" if key is EMPTY: return len(coll) == len(set(coll)) else: return len(coll) == len(set(xmap(key, coll)))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L189-L194
29
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
97.641509
6
2
100
1
def is_distinct(coll, key=EMPTY): if key is EMPTY: return len(coll) == len(set(coll)) else: return len(coll) == len(set(xmap(key, coll)))
20,116
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
all
(pred, seq=EMPTY)
return _all(xmap(pred, seq))
Checks if all items in seq pass pred (or are truthy).
Checks if all items in seq pass pred (or are truthy).
197
201
def all(pred, seq=EMPTY): """Checks if all items in seq pass pred (or are truthy).""" if seq is EMPTY: return _all(pred) return _all(xmap(pred, seq))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L197-L201
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.641509
5
2
100
1
def all(pred, seq=EMPTY): if seq is EMPTY: return _all(pred) return _all(xmap(pred, seq))
20,117
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
any
(pred, seq=EMPTY)
return _any(xmap(pred, seq))
Checks if any item in seq passes pred (or is truthy).
Checks if any item in seq passes pred (or is truthy).
203
207
def any(pred, seq=EMPTY): """Checks if any item in seq passes pred (or is truthy).""" if seq is EMPTY: return _any(pred) return _any(xmap(pred, seq))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L203-L207
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.641509
5
2
100
1
def any(pred, seq=EMPTY): if seq is EMPTY: return _any(pred) return _any(xmap(pred, seq))
20,118
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
none
(pred, seq=EMPTY)
return not any(pred, seq)
Checks if none of the items in seq pass pred (or are truthy).
Checks if none of the items in seq pass pred (or are truthy).
209
211
def none(pred, seq=EMPTY): """"Checks if none of the items in seq pass pred (or are truthy).""" return not any(pred, seq)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L209-L211
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def none(pred, seq=EMPTY): return not any(pred, seq)
20,119
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
one
(pred, seq=EMPTY)
return len(take(2, xfilter(pred, seq))) == 1
Checks whether exactly one item in seq passes pred (or is truthy).
Checks whether exactly one item in seq passes pred (or is truthy).
213
217
def one(pred, seq=EMPTY): """Checks whether exactly one item in seq passes pred (or is truthy).""" if seq is EMPTY: return one(bool, pred) return len(take(2, xfilter(pred, seq))) == 1
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L213-L217
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.641509
5
2
100
1
def one(pred, seq=EMPTY): if seq is EMPTY: return one(bool, pred) return len(take(2, xfilter(pred, seq))) == 1
20,120
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
some
(pred, seq=EMPTY)
return next(xfilter(pred, seq), None)
Finds first item in seq passing pred or first that is truthy.
Finds first item in seq passing pred or first that is truthy.
220
224
def some(pred, seq=EMPTY): """Finds first item in seq passing pred or first that is truthy.""" if seq is EMPTY: return some(bool, pred) return next(xfilter(pred, seq), None)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L220-L224
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.641509
5
2
100
1
def some(pred, seq=EMPTY): if seq is EMPTY: return some(bool, pred) return next(xfilter(pred, seq), None)
20,121
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
zipdict
(keys, vals)
return dict(zip(keys, vals))
Creates a dict with keys mapped to the corresponding vals.
Creates a dict with keys mapped to the corresponding vals.
233
235
def zipdict(keys, vals): """Creates a dict with keys mapped to the corresponding vals.""" return dict(zip(keys, vals))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L233-L235
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def zipdict(keys, vals): return dict(zip(keys, vals))
20,122
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
flip
(mapping)
return walk(flip_pair, mapping)
Flip passed dict or collection of pairs swapping its keys and values.
Flip passed dict or collection of pairs swapping its keys and values.
237
242
def flip(mapping): """Flip passed dict or collection of pairs swapping its keys and values.""" def flip_pair(pair): k, v = pair return v, k return walk(flip_pair, mapping)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L237-L242
29
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
97.641509
6
2
100
1
def flip(mapping): def flip_pair(pair): k, v = pair return v, k return walk(flip_pair, mapping)
20,123
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
project
(mapping, keys)
return _factory(mapping)((k, mapping[k]) for k in keys if k in mapping)
Leaves only given keys in mapping.
Leaves only given keys in mapping.
244
246
def project(mapping, keys): """Leaves only given keys in mapping.""" return _factory(mapping)((k, mapping[k]) for k in keys if k in mapping)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L244-L246
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def project(mapping, keys): return _factory(mapping)((k, mapping[k]) for k in keys if k in mapping)
20,124
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
omit
(mapping, keys)
return _factory(mapping)((k, v) for k, v in iteritems(mapping) if k not in keys)
Removes given keys from mapping.
Removes given keys from mapping.
248
250
def omit(mapping, keys): """Removes given keys from mapping.""" return _factory(mapping)((k, v) for k, v in iteritems(mapping) if k not in keys)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L248-L250
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def omit(mapping, keys): return _factory(mapping)((k, v) for k, v in iteritems(mapping) if k not in keys)
20,125
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
zip_values
(*dicts)
Yields tuples of corresponding values of several dicts.
Yields tuples of corresponding values of several dicts.
252
258
def zip_values(*dicts): """Yields tuples of corresponding values of several dicts.""" if len(dicts) < 1: raise TypeError('zip_values expects at least one argument') keys = set.intersection(*map(set, dicts)) for key in keys: yield tuple(d[key] for d in dicts)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L252-L258
29
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
97.641509
7
3
100
1
def zip_values(*dicts): if len(dicts) < 1: raise TypeError('zip_values expects at least one argument') keys = set.intersection(*map(set, dicts)) for key in keys: yield tuple(d[key] for d in dicts)
20,126
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
zip_dicts
(*dicts)
Yields tuples like (key, (val1, val2, ...)) for each common key in all given dicts.
Yields tuples like (key, (val1, val2, ...)) for each common key in all given dicts.
260
267
def zip_dicts(*dicts): """Yields tuples like (key, (val1, val2, ...)) for each common key in all given dicts.""" if len(dicts) < 1: raise TypeError('zip_dicts expects at least one argument') keys = set.intersection(*map(set, dicts)) for key in keys: yield key, tuple(d[key] for d in dicts)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L260-L267
29
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
97.641509
8
3
100
2
def zip_dicts(*dicts): if len(dicts) < 1: raise TypeError('zip_dicts expects at least one argument') keys = set.intersection(*map(set, dicts)) for key in keys: yield key, tuple(d[key] for d in dicts)
20,127
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
get_in
(coll, path, default=None)
return coll
Returns a value at path in the given nested collection.
Returns a value at path in the given nested collection.
269
276
def get_in(coll, path, default=None): """Returns a value at path in the given nested collection.""" for key in path: try: coll = coll[key] except (KeyError, IndexError): return default return coll
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L269-L276
29
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
97.641509
8
3
100
1
def get_in(coll, path, default=None): for key in path: try: coll = coll[key] except (KeyError, IndexError): return default return coll
20,128
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
set_in
(coll, path, value)
return update_in(coll, path, lambda _: value)
Creates a copy of coll with the value set at path.
Creates a copy of coll with the value set at path.
278
280
def set_in(coll, path, value): """Creates a copy of coll with the value set at path.""" return update_in(coll, path, lambda _: value)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L278-L280
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def set_in(coll, path, value): return update_in(coll, path, lambda _: value)
20,129
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
update_in
(coll, path, update, default=None)
Creates a copy of coll with a value updated at path.
Creates a copy of coll with a value updated at path.
282
295
def update_in(coll, path, update, default=None): """Creates a copy of coll with a value updated at path.""" if not path: return update(coll) elif isinstance(coll, list): copy = coll[:] # NOTE: there is no auto-vivication for lists copy[path[0]] = update_in(copy[path[0]], path[1:], update, default) return copy else: copy = coll.copy() current_default = {} if len(path) > 1 else default copy[path[0]] = update_in(copy.get(path[0], current_default), path[1:], update, default) return copy
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L282-L295
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
97.641509
14
3
100
1
def update_in(coll, path, update, default=None): if not path: return update(coll) elif isinstance(coll, list): copy = coll[:] # NOTE: there is no auto-vivication for lists copy[path[0]] = update_in(copy[path[0]], path[1:], update, default) return copy else: copy = coll.copy() current_default = {} if len(path) > 1 else default copy[path[0]] = update_in(copy.get(path[0], current_default), path[1:], update, default) return copy
20,130
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
del_in
(coll, path)
return coll_copy
Creates a copy of coll with a nested key or index deleted.
Creates a copy of coll with a nested key or index deleted.
298
312
def del_in(coll, path): """Creates a copy of coll with a nested key or index deleted.""" if not path: return coll try: next_coll = coll[path[0]] except (KeyError, IndexError): return coll coll_copy = copy(coll) if len(path) == 1: del coll_copy[path[0]] else: coll_copy[path[0]] = del_in(next_coll, path[1:]) return coll_copy
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L298-L312
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
97.641509
15
4
100
1
def del_in(coll, path): if not path: return coll try: next_coll = coll[path[0]] except (KeyError, IndexError): return coll coll_copy = copy(coll) if len(path) == 1: del coll_copy[path[0]] else: coll_copy[path[0]] = del_in(next_coll, path[1:]) return coll_copy
20,131
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
has_path
(coll, path)
return True
Checks if path exists in the given nested collection.
Checks if path exists in the given nested collection.
315
322
def has_path(coll, path): """Checks if path exists in the given nested collection.""" for p in path: try: coll = coll[p] except (KeyError, IndexError): return False return True
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L315-L322
29
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
97.641509
8
3
100
1
def has_path(coll, path): for p in path: try: coll = coll[p] except (KeyError, IndexError): return False return True
20,132
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
lwhere
(mappings, **cond)
return list(where(mappings, **cond))
Selects mappings containing all pairs in cond.
Selects mappings containing all pairs in cond.
324
326
def lwhere(mappings, **cond): """Selects mappings containing all pairs in cond.""" return list(where(mappings, **cond))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L324-L326
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def lwhere(mappings, **cond): return list(where(mappings, **cond))
20,133
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
lpluck
(key, mappings)
return list(pluck(key, mappings))
Lists values for key in each mapping.
Lists values for key in each mapping.
328
330
def lpluck(key, mappings): """Lists values for key in each mapping.""" return list(pluck(key, mappings))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L328-L330
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def lpluck(key, mappings): return list(pluck(key, mappings))
20,134
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
lpluck_attr
(attr, objects)
return list(pluck_attr(attr, objects))
Lists values of given attribute of each object.
Lists values of given attribute of each object.
332
334
def lpluck_attr(attr, objects): """Lists values of given attribute of each object.""" return list(pluck_attr(attr, objects))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L332-L334
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def lpluck_attr(attr, objects): return list(pluck_attr(attr, objects))
20,135
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
linvoke
(objects, name, *args, **kwargs)
return list(invoke(objects, name, *args, **kwargs))
Makes a list of results of the obj.name(*args, **kwargs) for each object in objects.
Makes a list of results of the obj.name(*args, **kwargs) for each object in objects.
336
339
def linvoke(objects, name, *args, **kwargs): """Makes a list of results of the obj.name(*args, **kwargs) for each object in objects.""" return list(invoke(objects, name, *args, **kwargs))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L336-L339
29
[ 0, 1, 2, 3 ]
100
[]
0
true
97.641509
4
1
100
2
def linvoke(objects, name, *args, **kwargs): return list(invoke(objects, name, *args, **kwargs))
20,136
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
where
(mappings, **cond)
return filter(match, mappings)
Iterates over mappings containing all pairs in cond.
Iterates over mappings containing all pairs in cond.
344
348
def where(mappings, **cond): """Iterates over mappings containing all pairs in cond.""" items = cond.items() match = lambda m: all(k in m and m[k] == v for k, v in items) return filter(match, mappings)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L344-L348
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.641509
5
2
100
1
def where(mappings, **cond): items = cond.items() match = lambda m: all(k in m and m[k] == v for k, v in items) return filter(match, mappings)
20,137
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
pluck
(key, mappings)
return map(itemgetter(key), mappings)
Iterates over values for key in mappings.
Iterates over values for key in mappings.
350
352
def pluck(key, mappings): """Iterates over values for key in mappings.""" return map(itemgetter(key), mappings)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L350-L352
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def pluck(key, mappings): return map(itemgetter(key), mappings)
20,138
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
pluck_attr
(attr, objects)
return map(attrgetter(attr), objects)
Iterates over values of given attribute of given objects.
Iterates over values of given attribute of given objects.
354
356
def pluck_attr(attr, objects): """Iterates over values of given attribute of given objects.""" return map(attrgetter(attr), objects)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L354-L356
29
[ 0, 1, 2 ]
100
[]
0
true
97.641509
3
1
100
1
def pluck_attr(attr, objects): return map(attrgetter(attr), objects)
20,139
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/colls.py
invoke
(objects, name, *args, **kwargs)
return map(methodcaller(name, *args, **kwargs), objects)
Yields results of the obj.name(*args, **kwargs) for each object in objects.
Yields results of the obj.name(*args, **kwargs) for each object in objects.
358
361
def invoke(objects, name, *args, **kwargs): """Yields results of the obj.name(*args, **kwargs) for each object in objects.""" return map(methodcaller(name, *args, **kwargs), objects)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/colls.py#L358-L361
29
[ 0, 1, 2, 3 ]
100
[]
0
true
97.641509
4
1
100
2
def invoke(objects, name, *args, **kwargs): return map(methodcaller(name, *args, **kwargs), objects)
20,140
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
_make_getter
(regex)
13
23
def _make_getter(regex): if regex.groups == 0: return methodcaller('group') elif regex.groups == 1 and regex.groupindex == {}: return methodcaller('group', 1) elif regex.groupindex == {}: return methodcaller('groups') elif regex.groups == len(regex.groupindex): return methodcaller('groupdict') else: return lambda m: m
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L13-L23
29
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
81.818182
[ 10 ]
9.090909
false
95.555556
11
6
90.909091
0
def _make_getter(regex): if regex.groups == 0: return methodcaller('group') elif regex.groups == 1 and regex.groupindex == {}: return methodcaller('group', 1) elif regex.groupindex == {}: return methodcaller('groups') elif regex.groups == len(regex.groupindex): return methodcaller('groupdict') else: return lambda m: m
20,141
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
_prepare
(regex, flags)
return regex, _make_getter(regex)
27
30
def _prepare(regex, flags): if not isinstance(regex, _re_type): regex = re.compile(regex, flags) return regex, _make_getter(regex)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L27-L30
29
[ 0, 1, 2, 3 ]
100
[]
0
true
95.555556
4
2
100
0
def _prepare(regex, flags): if not isinstance(regex, _re_type): regex = re.compile(regex, flags) return regex, _make_getter(regex)
20,142
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
re_iter
(regex, s, flags=0)
return map(getter, regex.finditer(s))
Iterates over matches of regex in s, presents them in simplest possible form
Iterates over matches of regex in s, presents them in simplest possible form
33
36
def re_iter(regex, s, flags=0): """Iterates over matches of regex in s, presents them in simplest possible form""" regex, getter = _prepare(regex, flags) return map(getter, regex.finditer(s))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L33-L36
29
[ 0, 1, 2, 3 ]
100
[]
0
true
95.555556
4
1
100
1
def re_iter(regex, s, flags=0): regex, getter = _prepare(regex, flags) return map(getter, regex.finditer(s))
20,143
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
re_all
(regex, s, flags=0)
return list(re_iter(regex, s, flags))
Lists all matches of regex in s, presents them in simplest possible form
Lists all matches of regex in s, presents them in simplest possible form
38
40
def re_all(regex, s, flags=0): """Lists all matches of regex in s, presents them in simplest possible form""" return list(re_iter(regex, s, flags))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L38-L40
29
[ 0, 1, 2 ]
100
[]
0
true
95.555556
3
1
100
1
def re_all(regex, s, flags=0): return list(re_iter(regex, s, flags))
20,144
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
re_find
(regex, s, flags=0)
return re_finder(regex, flags)(s)
Matches regex against the given string, returns the match in the simplest possible form.
Matches regex against the given string, returns the match in the simplest possible form.
42
45
def re_find(regex, s, flags=0): """Matches regex against the given string, returns the match in the simplest possible form.""" return re_finder(regex, flags)(s)
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L42-L45
29
[ 0, 1, 2, 3 ]
100
[]
0
true
95.555556
4
1
100
2
def re_find(regex, s, flags=0): return re_finder(regex, flags)(s)
20,145
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
re_finder
(regex, flags=0)
return lambda s: getter(regex.search(s))
Creates a function finding regex in passed string.
Creates a function finding regex in passed string.
52
56
def re_finder(regex, flags=0): """Creates a function finding regex in passed string.""" regex, _getter = _prepare(regex, flags) getter = lambda m: _getter(m) if m else None return lambda s: getter(regex.search(s))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L52-L56
29
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
95.555556
5
1
100
1
def re_finder(regex, flags=0): regex, _getter = _prepare(regex, flags) getter = lambda m: _getter(m) if m else None return lambda s: getter(regex.search(s))
20,146
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
str_join
(sep, seq=EMPTY)
Joins the given sequence with sep. Forces stringification of seq items.
Joins the given sequence with sep. Forces stringification of seq items.
65
71
def str_join(sep, seq=EMPTY): """Joins the given sequence with sep. Forces stringification of seq items.""" if seq is EMPTY: return str_join('', sep) else: return sep.join(map(sep.__class__, seq))
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L65-L71
29
[ 0, 1, 2, 3, 4, 6 ]
85.714286
[]
0
false
95.555556
7
2
100
2
def str_join(sep, seq=EMPTY): if seq is EMPTY: return str_join('', sep) else: return sep.join(map(sep.__class__, seq))
20,147
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
cut_prefix
(s, prefix)
return s[len(prefix):] if s.startswith(prefix) else s
Cuts prefix from given string if it's present.
Cuts prefix from given string if it's present.
73
75
def cut_prefix(s, prefix): """Cuts prefix from given string if it's present.""" return s[len(prefix):] if s.startswith(prefix) else s
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L73-L75
29
[ 0, 1, 2 ]
100
[]
0
true
95.555556
3
1
100
1
def cut_prefix(s, prefix): return s[len(prefix):] if s.startswith(prefix) else s
20,148
Suor/funcy
5f23815f224e595b8a54822bcb330cd31a799c78
funcy/strings.py
cut_suffix
(s, suffix)
return s[:-len(suffix)] if s.endswith(suffix) else s
Cuts suffix from given string if it's present.
Cuts suffix from given string if it's present.
77
79
def cut_suffix(s, suffix): """Cuts suffix from given string if it's present.""" return s[:-len(suffix)] if s.endswith(suffix) else s
https://github.com/Suor/funcy/blob/5f23815f224e595b8a54822bcb330cd31a799c78/project29/funcy/strings.py#L77-L79
29
[ 0, 1, 2 ]
100
[]
0
true
95.555556
3
1
100
1
def cut_suffix(s, suffix): return s[:-len(suffix)] if s.endswith(suffix) else s
20,149
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/trim_docstring.py
trim_docstring
(docstring)
return inspect.cleandoc(docstring) if docstring else None
4
9
def trim_docstring(docstring): # Cleans up whitespaces from an indented docstring # # See https://www.python.org/dev/peps/pep-0257/ # and https://docs.python.org/2/library/inspect.html#inspect.cleandoc return inspect.cleandoc(docstring) if docstring else None
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/trim_docstring.py#L4-L9
30
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
100
6
1
100
0
def trim_docstring(docstring): # Cleans up whitespaces from an indented docstring # # See https://www.python.org/dev/peps/pep-0257/ # and https://docs.python.org/2/library/inspect.html#inspect.cleandoc return inspect.cleandoc(docstring) if docstring else None
20,642
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/thenables.py
await_and_execute
(obj, on_resolve)
return build_resolve_async()
8
12
def await_and_execute(obj, on_resolve): async def build_resolve_async(): return on_resolve(await obj) return build_resolve_async()
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/thenables.py#L8-L12
30
[ 0 ]
20
[ 1, 2, 4 ]
60
false
33.333333
5
2
40
0
def await_and_execute(obj, on_resolve): async def build_resolve_async(): return on_resolve(await obj) return build_resolve_async()
20,657
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/thenables.py
maybe_thenable
(obj, on_resolve)
return on_resolve(obj)
Execute a on_resolve function once the thenable is resolved, returning the same type of object inputed. If the object is not thenable, it should return on_resolve(obj)
Execute a on_resolve function once the thenable is resolved, returning the same type of object inputed. If the object is not thenable, it should return on_resolve(obj)
15
25
def maybe_thenable(obj, on_resolve): """ Execute a on_resolve function once the thenable is resolved, returning the same type of object inputed. If the object is not thenable, it should return on_resolve(obj) """ if isawaitable(obj): return await_and_execute(obj, on_resolve) # If it's not awaitable, return the function executed over the object return on_resolve(obj)
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/thenables.py#L15-L25
30
[ 0, 1, 2, 3, 4, 5 ]
54.545455
[ 6, 7, 10 ]
27.272727
false
33.333333
11
2
72.727273
3
def maybe_thenable(obj, on_resolve): if isawaitable(obj): return await_and_execute(obj, on_resolve) # If it's not awaitable, return the function executed over the object return on_resolve(obj)
20,658
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/str_converters.py
to_camel_case
(snake_str)
return components[0] + "".join(x.capitalize() if x else "_" for x in components[1:])
6
10
def to_camel_case(snake_str): components = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'capitalize' method and join them together. return components[0] + "".join(x.capitalize() if x else "_" for x in components[1:])
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/str_converters.py#L6-L10
30
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
71.428571
5
1
100
0
def to_camel_case(snake_str): components = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'capitalize' method and join them together. return components[0] + "".join(x.capitalize() if x else "_" for x in components[1:])
20,660
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/str_converters.py
to_snake_case
(name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
15
17
def to_snake_case(name): s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/str_converters.py#L15-L17
30
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
71.428571
3
1
33.333333
0
def to_snake_case(name): s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
20,661
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/deprecated.py
warn_deprecation
(text)
8
9
def warn_deprecation(text): warnings.warn(text, category=DeprecationWarning, stacklevel=2)
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/deprecated.py#L8-L9
30
[ 0 ]
50
[ 1 ]
50
false
48.275862
2
1
50
0
def warn_deprecation(text): warnings.warn(text, category=DeprecationWarning, stacklevel=2)
20,662
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/deprecated.py
deprecated
(reason)
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
12
70
def deprecated(reason): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. """ if isinstance(reason, string_types): # The @deprecated is used with a 'reason'. # # .. code-block:: python # # @deprecated("please, use another function") # def old_function(x, y): # pass def decorator(func1): if inspect.isclass(func1): fmt1 = f"Call to deprecated class {func1.__name__} ({reason})." else: fmt1 = f"Call to deprecated function {func1.__name__} ({reason})." @functools.wraps(func1) def new_func1(*args, **kwargs): warn_deprecation(fmt1) return func1(*args, **kwargs) return new_func1 return decorator elif inspect.isclass(reason) or inspect.isfunction(reason): # The @deprecated is used without any 'reason'. # # .. code-block:: python # # @deprecated # def old_function(x, y): # pass func2 = reason if inspect.isclass(func2): fmt2 = f"Call to deprecated class {func2.__name__}." else: fmt2 = f"Call to deprecated function {func2.__name__}." @functools.wraps(func2) def new_func2(*args, **kwargs): warn_deprecation(fmt2) return func2(*args, **kwargs) return new_func2 else: raise TypeError(repr(type(reason)))
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/deprecated.py#L12-L70
30
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 28, 29, 30, 31, 32 ]
50.847458
[ 20, 26, 27, 33, 43, 45, 46, 48, 50, 51, 52, 53, 55, 58 ]
23.728814
false
48.275862
59
9
76.271186
3
def deprecated(reason): if isinstance(reason, string_types): # The @deprecated is used with a 'reason'. # # .. code-block:: python # # @deprecated("please, use another function") # def old_function(x, y): # pass def decorator(func1): if inspect.isclass(func1): fmt1 = f"Call to deprecated class {func1.__name__} ({reason})." else: fmt1 = f"Call to deprecated function {func1.__name__} ({reason})." @functools.wraps(func1) def new_func1(*args, **kwargs): warn_deprecation(fmt1) return func1(*args, **kwargs) return new_func1 return decorator elif inspect.isclass(reason) or inspect.isfunction(reason): # The @deprecated is used without any 'reason'. # # .. code-block:: python # # @deprecated # def old_function(x, y): # pass func2 = reason if inspect.isclass(func2): fmt2 = f"Call to deprecated class {func2.__name__}." else: fmt2 = f"Call to deprecated function {func2.__name__}." @functools.wraps(func2) def new_func2(*args, **kwargs): warn_deprecation(fmt2) return func2(*args, **kwargs) return new_func2 else: raise TypeError(repr(type(reason)))
20,663
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/module_loading.py
import_string
(dotted_path, dotted_attributes=None)
Import a dotted module path and return the attribute/class designated by the last name in the path. When a dotted attribute path is also provided, the dotted attribute path would be applied to the attribute/class retrieved from the first step, and return the corresponding value designated by the attribute path. Raise ImportError if the import failed.
Import a dotted module path and return the attribute/class designated by the last name in the path. When a dotted attribute path is also provided, the dotted attribute path would be applied to the attribute/class retrieved from the first step, and return the corresponding value designated by the attribute path. Raise ImportError if the import failed.
5
41
def import_string(dotted_path, dotted_attributes=None): """ Import a dotted module path and return the attribute/class designated by the last name in the path. When a dotted attribute path is also provided, the dotted attribute path would be applied to the attribute/class retrieved from the first step, and return the corresponding value designated by the attribute path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit(".", 1) except ValueError: raise ImportError("%s doesn't look like a module path" % dotted_path) module = import_module(module_path) try: result = getattr(module, class_name) except AttributeError: raise ImportError( 'Module "%s" does not define a "%s" attribute/class' % (module_path, class_name) ) if not dotted_attributes: return result attributes = dotted_attributes.split(".") traveled_attributes = [] try: for attribute in attributes: traveled_attributes.append(attribute) result = getattr(result, attribute) return result except AttributeError: raise ImportError( 'Module "%s" does not define a "%s" attribute inside attribute/class "%s"' % (module_path, ".".join(traveled_attributes), class_name) )
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/module_loading.py#L5-L41
30
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
21.621622
[ 8, 9, 10, 11, 13, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
54.054054
false
16
37
6
45.945946
5
def import_string(dotted_path, dotted_attributes=None): try: module_path, class_name = dotted_path.rsplit(".", 1) except ValueError: raise ImportError("%s doesn't look like a module path" % dotted_path) module = import_module(module_path) try: result = getattr(module, class_name) except AttributeError: raise ImportError( 'Module "%s" does not define a "%s" attribute/class' % (module_path, class_name) ) if not dotted_attributes: return result attributes = dotted_attributes.split(".") traveled_attributes = [] try: for attribute in attributes: traveled_attributes.append(attribute) result = getattr(result, attribute) return result except AttributeError: raise ImportError( 'Module "%s" does not define a "%s" attribute inside attribute/class "%s"' % (module_path, ".".join(traveled_attributes), class_name) )
20,664
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/module_loading.py
lazy_import
(dotted_path, dotted_attributes=None)
return partial(import_string, dotted_path, dotted_attributes)
44
45
def lazy_import(dotted_path, dotted_attributes=None): return partial(import_string, dotted_path, dotted_attributes)
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/module_loading.py#L44-L45
30
[ 0 ]
50
[ 1 ]
50
false
16
2
1
50
0
def lazy_import(dotted_path, dotted_attributes=None): return partial(import_string, dotted_path, dotted_attributes)
20,665
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/props.py
props
(x)
return { key: vars(x).get(key, getattr(x, key)) for key in dir(x) if key not in _all_vars }
12
15
def props(x): return { key: vars(x).get(key, getattr(x, key)) for key in dir(x) if key not in _all_vars }
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/props.py#L12-L15
30
[ 0, 1 ]
50
[]
0
false
100
4
1
100
0
def props(x): return { key: vars(x).get(key, getattr(x, key)) for key in dir(x) if key not in _all_vars }
20,667
graphql-python/graphene
52143473efad141f6700237ecce79b22e8ff4e41
graphene/utils/get_unbound_function.py
get_unbound_function
(func)
return func
1
4
def get_unbound_function(func): if not getattr(func, "__self__", True): return func.__func__ return func
https://github.com/graphql-python/graphene/blob/52143473efad141f6700237ecce79b22e8ff4e41/project30/graphene/utils/get_unbound_function.py#L1-L4
30
[ 0, 1, 3 ]
75
[ 2 ]
25
false
75
4
2
75
0
def get_unbound_function(func): if not getattr(func, "__self__", True): return func.__func__ return func
20,668