code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
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))
Joins the given sequence with sep. Forces stringification of seq items.
str_join
python
Suor/funcy
funcy/strings.py
https://github.com/Suor/funcy/blob/master/funcy/strings.py
BSD-3-Clause
def cut_prefix(s, prefix): """Cuts prefix from given string if it's present.""" return s[len(prefix):] if s.startswith(prefix) else s
Cuts prefix from given string if it's present.
cut_prefix
python
Suor/funcy
funcy/strings.py
https://github.com/Suor/funcy/blob/master/funcy/strings.py
BSD-3-Clause
def cut_suffix(s, suffix): """Cuts suffix from given string if it's present.""" return s[:-len(suffix)] if s.endswith(suffix) else s
Cuts suffix from given string if it's present.
cut_suffix
python
Suor/funcy
funcy/strings.py
https://github.com/Suor/funcy/blob/master/funcy/strings.py
BSD-3-Clause
def wrap_prop(ctx): """Wrap a property accessors with a context manager""" def decorator(prop): class WrapperProp(object): def __repr__(self): return repr(prop) def __get__(self, instance, type=None): if instance is None: return self with ctx: return prop.__get__(instance, type) if hasattr(prop, '__set__'): def __set__(self, name, value): with ctx: return prop.__set__(name, value) if hasattr(prop, '__del__'): def __del__(self, name): with ctx: return prop.__del__(name) return WrapperProp() return decorator
Wrap a property accessors with a context manager
wrap_prop
python
Suor/funcy
funcy/objects.py
https://github.com/Suor/funcy/blob/master/funcy/objects.py
BSD-3-Clause
def monkey(cls, name=None): """ Monkey patches class or module by adding to it decorated function. Anything overwritten could be accessed via .original attribute of decorated object. """ assert isclass(cls) or ismodule(cls), "Attempting to monkey patch non-class and non-module" def decorator(value): func = getattr(value, 'fget', value) # Support properties func_name = name or cut_prefix(func.__name__, '%s__' % cls.__name__) func.__name__ = func_name func.original = getattr(cls, func_name, None) setattr(cls, func_name, value) return value return decorator
Monkey patches class or module by adding to it decorated function. Anything overwritten could be accessed via .original attribute of decorated object.
monkey
python
Suor/funcy
funcy/objects.py
https://github.com/Suor/funcy/blob/master/funcy/objects.py
BSD-3-Clause
def isa(*types): """ Creates a function checking if its argument is of any of given types. """ return lambda x: isinstance(x, types)
Creates a function checking if its argument is of any of given types.
isa
python
Suor/funcy
funcy/types.py
https://github.com/Suor/funcy/blob/master/funcy/types.py
BSD-3-Clause
def tree_leaves(root, follow=is_seqcont, children=iter): """Iterates over tree leaves.""" q = deque([[root]]) while q: node_iter = iter(q.pop()) for sub in node_iter: if follow(sub): q.append(node_iter) q.append(children(sub)) break else: yield sub
Iterates over tree leaves.
tree_leaves
python
Suor/funcy
funcy/tree.py
https://github.com/Suor/funcy/blob/master/funcy/tree.py
BSD-3-Clause
def ltree_leaves(root, follow=is_seqcont, children=iter): """Lists tree leaves.""" return list(tree_leaves(root, follow, children))
Lists tree leaves.
ltree_leaves
python
Suor/funcy
funcy/tree.py
https://github.com/Suor/funcy/blob/master/funcy/tree.py
BSD-3-Clause
def tree_nodes(root, follow=is_seqcont, children=iter): """Iterates over all tree nodes.""" q = deque([[root]]) while q: node_iter = iter(q.pop()) for sub in node_iter: yield sub if follow(sub): q.append(node_iter) q.append(children(sub)) break
Iterates over all tree nodes.
tree_nodes
python
Suor/funcy
funcy/tree.py
https://github.com/Suor/funcy/blob/master/funcy/tree.py
BSD-3-Clause
def ltree_nodes(root, follow=is_seqcont, children=iter): """Lists all tree nodes.""" return list(tree_nodes(root, follow, children))
Lists all tree nodes.
ltree_nodes
python
Suor/funcy
funcy/tree.py
https://github.com/Suor/funcy/blob/master/funcy/tree.py
BSD-3-Clause
def identity(x): """Returns its argument.""" return x
Returns its argument.
identity
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
def constantly(x): """Creates a function accepting any args, but always returning x.""" return lambda *a, **kw: x
Creates a function accepting any args, but always returning x.
constantly
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
def caller(*a, **kw): """Creates a function calling its sole argument with given *a, **kw.""" return lambda f: f(*a, **kw)
Creates a function calling its sole argument with given *a, **kw.
caller
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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))
A functools.partial alternative, which returns a real function. Can be used to construct methods.
func_partial
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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))
Partially applies last arguments. New keyworded arguments extend and override kwargs.
rpartial
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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)
Curries func into a chain of one argument functions.
curry
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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)
Curries func into a chain of one argument functions. Arguments are passed from right to left.
rcurry
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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.varkw 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
Creates a version of func returning its partial applications until sufficient arguments are passed.
autocurry
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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
Creates a function, which conditionally applies action or default.
iffy
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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
Composes passed functions.
compose
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
def rcompose(*fs): """Composes functions, calling them from left to right.""" return compose(*reversed(fs))
Composes functions, calling them from left to right.
rcompose
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
def complement(pred): """Constructs a complementary predicate.""" return compose(__not__, pred)
Constructs a complementary predicate.
complement
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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]
Constructs a juxtaposition of the given functions. Result returns a list of results of fs.
ljuxt
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
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)
Constructs a lazy juxtaposition of the given functions. Result returns an iterator of results of fs.
juxt
python
Suor/funcy
funcy/funcs.py
https://github.com/Suor/funcy/blob/master/funcy/funcs.py
BSD-3-Clause
def decorator(deco): """ Transforms a flat wrapper into decorator:: @decorator def func(call, methods, content_type=DEFAULT): # These are decorator params # Access call arg by name if call.request.method not in methods: # ... # Decorated functions and all the arguments are accesible as: print(call._func, call_args, call._kwargs) # Finally make a call: return call() """ if has_single_arg(deco): return make_decorator(deco) elif has_1pos_and_kwonly(deco): # Any arguments after first become decorator arguments # And a decorator with arguments is essentially a decorator fab # TODO: use pos-only arg once in Python 3.8+ only def decorator_fab(_func=None, **dkwargs): if _func is not None: return make_decorator(deco, (), dkwargs)(_func) return make_decorator(deco, (), dkwargs) else: def decorator_fab(*dargs, **dkwargs): return make_decorator(deco, dargs, dkwargs) return wraps(deco)(decorator_fab)
Transforms a flat wrapper into decorator:: @decorator def func(call, methods, content_type=DEFAULT): # These are decorator params # Access call arg by name if call.request.method not in methods: # ... # Decorated functions and all the arguments are accesible as: print(call._func, call_args, call._kwargs) # Finally make a call: return call()
decorator
python
Suor/funcy
funcy/decorators.py
https://github.com/Suor/funcy/blob/master/funcy/decorators.py
BSD-3-Clause
def all_fn(*fs): """Constructs a predicate, which holds when all fs hold.""" return compose(all, juxt(*fs))
Constructs a predicate, which holds when all fs hold.
all_fn
python
Suor/funcy
funcy/funcolls.py
https://github.com/Suor/funcy/blob/master/funcy/funcolls.py
BSD-3-Clause
def any_fn(*fs): """Constructs a predicate, which holds when any fs holds.""" return compose(any, juxt(*fs))
Constructs a predicate, which holds when any fs holds.
any_fn
python
Suor/funcy
funcy/funcolls.py
https://github.com/Suor/funcy/blob/master/funcy/funcolls.py
BSD-3-Clause
def none_fn(*fs): """Constructs a predicate, which holds when none of fs hold.""" return compose(none, juxt(*fs))
Constructs a predicate, which holds when none of fs hold.
none_fn
python
Suor/funcy
funcy/funcolls.py
https://github.com/Suor/funcy/blob/master/funcy/funcolls.py
BSD-3-Clause
def one_fn(*fs): """Constructs a predicate, which holds when exactly one of fs holds.""" return compose(one, juxt(*fs))
Constructs a predicate, which holds when exactly one of fs holds.
one_fn
python
Suor/funcy
funcy/funcolls.py
https://github.com/Suor/funcy/blob/master/funcy/funcolls.py
BSD-3-Clause
def some_fn(*fs): """Constructs a function, which calls fs one by one and returns first truthy result.""" return compose(some, juxt(*fs))
Constructs a function, which calls fs one by one and returns first truthy result.
some_fn
python
Suor/funcy
funcy/funcolls.py
https://github.com/Suor/funcy/blob/master/funcy/funcolls.py
BSD-3-Clause
def tap(x, label=None): """Prints x and then returns it.""" if label: print('%s: %s' % (label, x)) else: print(x) return x
Prints x and then returns it.
tap
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
def log_calls(call, print_func, errors=True, stack=True, repr_len=REPR_LEN): """Logs or prints all function calls, including arguments, results and raised exceptions.""" signature = signature_repr(call, repr_len) try: print_func('Call %s' % signature) result = call() # NOTE: using full repr of result print_func('-> %s from %s' % (smart_repr(result, max_len=None), signature)) return result except BaseException as e: if errors: print_func('-> ' + _format_error(signature, e, stack)) raise
Logs or prints all function calls, including arguments, results and raised exceptions.
log_calls
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
def log_enters(call, print_func, repr_len=REPR_LEN): """Logs each entrance to a function.""" print_func('Call %s' % signature_repr(call, repr_len)) return call()
Logs each entrance to a function.
log_enters
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
def print_enters(repr_len=REPR_LEN): """Prints on each entrance to a function.""" if callable(repr_len): return log_enters(print)(repr_len) else: return log_enters(print, repr_len)
Prints on each entrance to a function.
print_enters
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
def log_exits(call, print_func, errors=True, stack=True, repr_len=REPR_LEN): """Logs exits from a function.""" signature = signature_repr(call, repr_len) try: result = call() # NOTE: using full repr of result print_func('-> %s from %s' % (smart_repr(result, max_len=None), signature)) return result except BaseException as e: if errors: print_func('-> ' + _format_error(signature, e, stack)) raise
Logs exits from a function.
log_exits
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
def print_exits(errors=True, stack=True, repr_len=REPR_LEN): """Prints on exits from a function.""" if callable(errors): return log_exits(print)(errors) else: return log_exits(print, errors, stack, repr_len)
Prints on exits from a function.
print_exits
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
def log_iter_durations(seq, print_func, label=None, unit='auto'): """Times processing of each item in seq.""" if unit not in time_formatters: raise ValueError('Unknown time unit: %s. It should be ns, mks, ms, s or auto.' % unit) _format_time = time_formatters[unit] suffix = " of %s" % label if label else "" it = iter(seq) for i, item in enumerate(it): start = timer() yield item duration = _format_time(timer() - start) print_func("%s in iteration %d%s" % (duration, i, suffix))
Times processing of each item in seq.
log_iter_durations
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
def print_iter_durations(seq, label=None, unit='auto'): """Times processing of each item in seq.""" return log_iter_durations(seq, print, label, unit=unit)
Times processing of each item in seq.
print_iter_durations
python
Suor/funcy
funcy/debug.py
https://github.com/Suor/funcy/blob/master/funcy/debug.py
BSD-3-Clause
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
Constructs function that raises the given exception with given arguments on any invocation.
raiser
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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
Alters function to ignore given errors, returning default instead.
ignore
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
def silent(func): """Alters function to ignore all exceptions.""" return ignore(Exception)(func)
Alters function to ignore all exceptions.
silent
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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 into from e
Reraises errors as other exception.
reraise
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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)
Makes decorated function retry up to tries times. Retries only on specified errors. Sleeps timeout or timeout(attempt) seconds between tries.
retry
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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
Tries several approaches until one works. Each approach has a form of (callable, expected_errors).
fallback
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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)
Ensures that errors are passable to except clause. I.e. should be BaseException subclass or a tuple.
_ensure_exceptable
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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
If function fails to complete fails times in a row, calls to it will be intercepted for timeout with exception raised instead.
limit_error_rate
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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
Allows only one run in a period, the rest is skipped
throttle
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
def post_processing(call, func): """Post processes decorated function result with func.""" return func(call())
Post processes decorated function result with func.
post_processing
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
def joining(call, sep): """Joins decorated function results with sep.""" return sep.join(map(sep.__class__, call()))
Joins decorated function results with sep.
joining
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
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
Call function only once for every combination of the given arguments.
once_per
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
def once_per_args(func): """Call function once for every combination of values of its arguments.""" return once_per(*get_argnames(func))(func)
Call function once for every combination of values of its arguments.
once_per_args
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
def wrap_with(call, ctx): """Turn context manager into a decorator""" with ctx: return call()
Turn context manager into a decorator
wrap_with
python
Suor/funcy
funcy/flow.py
https://github.com/Suor/funcy/blob/master/funcy/flow.py
BSD-3-Clause
def repeatedly(f, n=EMPTY): """Takes a function of no args, presumably with side effects, and returns an infinite (or length n) iterator of calls to it.""" _repeat = repeat(None) if n is EMPTY else repeat(None, n) return (f() for _ in _repeat)
Takes a function of no args, presumably with side effects, and returns an infinite (or length n) iterator of calls to it.
repeatedly
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def iterate(f, x): """Returns an infinite iterator of `x, f(x), f(f(x)), ...`""" while True: yield x x = f(x)
Returns an infinite iterator of `x, f(x), f(f(x)), ...`
iterate
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def take(n, seq): """Returns a list of first n items in the sequence, or all items if there are fewer than n.""" return list(islice(seq, n))
Returns a list of first n items in the sequence, or all items if there are fewer than n.
take
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def drop(n, seq): """Skips first n items in the sequence, yields the rest.""" return islice(seq, n, None)
Skips first n items in the sequence, yields the rest.
drop
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def first(seq): """Returns the first item in the sequence. Returns None if the sequence is empty.""" return next(iter(seq), None)
Returns the first item in the sequence. Returns None if the sequence is empty.
first
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def second(seq): """Returns second item in the sequence. Returns None if there are less than two items in it.""" return first(rest(seq))
Returns second item in the sequence. Returns None if there are less than two items in it.
second
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def nth(n, seq): """Returns nth item in the sequence or None if no such item exists.""" try: return seq[n] except IndexError: return None except TypeError: return next(islice(seq, n, None), None)
Returns nth item in the sequence or None if no such item exists.
nth
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def last(seq): """Returns the last item in the sequence or iterator. Returns None if the sequence is empty.""" try: return seq[-1] except IndexError: return None except TypeError: item = None for item in seq: pass return item
Returns the last item in the sequence or iterator. Returns None if the sequence is empty.
last
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def rest(seq): """Skips first item in the sequence, yields the rest.""" return drop(1, seq)
Skips first item in the sequence, yields the rest.
rest
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def butlast(seq): """Iterates over all elements of the sequence but last.""" it = iter(seq) try: prev = next(it) except StopIteration: pass else: for item in it: yield prev prev = item
Iterates over all elements of the sequence but last.
butlast
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def ilen(seq): """Consumes an iterable not reading it into memory and returns the number of items.""" # NOTE: implementation borrowed from http://stackoverflow.com/a/15112059/753382 counter = count() deque(zip(seq, counter), maxlen=0) # (consume at C speed) return next(counter)
Consumes an iterable not reading it into memory and returns the number of items.
ilen
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lmap(f, *seqs): """An extended version of builtin map() returning a list. Derives a mapper from string, int, slice, dict or set.""" return _lmap(make_func(f), *seqs)
An extended version of builtin map() returning a list. Derives a mapper from string, int, slice, dict or set.
lmap
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lfilter(pred, seq): """An extended version of builtin filter() returning a list. Derives a predicate from string, int, slice, dict or set.""" return _lfilter(make_pred(pred), seq)
An extended version of builtin filter() returning a list. Derives a predicate from string, int, slice, dict or set.
lfilter
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def map(f, *seqs): """An extended version of builtin map(). Derives a mapper from string, int, slice, dict or set.""" return _map(make_func(f), *seqs)
An extended version of builtin map(). Derives a mapper from string, int, slice, dict or set.
map
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def filter(pred, seq): """An extended version of builtin filter(). Derives a predicate from string, int, slice, dict or set.""" return _filter(make_pred(pred), seq)
An extended version of builtin filter(). Derives a predicate from string, int, slice, dict or set.
filter
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lremove(pred, seq): """Creates a list if items passing given predicate.""" return list(remove(pred, seq))
Creates a list if items passing given predicate.
lremove
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def remove(pred, seq): """Iterates items passing given predicate.""" return filterfalse(make_pred(pred), seq)
Iterates items passing given predicate.
remove
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lkeep(f, seq=EMPTY): """Maps seq with f and keeps only truthy results. Simply lists truthy values in one argument version.""" return list(keep(f, seq))
Maps seq with f and keeps only truthy results. Simply lists truthy values in one argument version.
lkeep
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def keep(f, seq=EMPTY): """Maps seq with f and iterates truthy results. Simply iterates truthy values in one argument version.""" if seq is EMPTY: return _filter(bool, f) else: return _filter(bool, map(f, seq))
Maps seq with f and iterates truthy results. Simply iterates truthy values in one argument version.
keep
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def without(seq, *items): """Iterates over sequence skipping items.""" for value in seq: if value not in items: yield value
Iterates over sequence skipping items.
without
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lwithout(seq, *items): """Removes items from sequence, preserves order.""" return list(without(seq, *items))
Removes items from sequence, preserves order.
lwithout
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lconcat(*seqs): """Concatenates several sequences.""" return list(chain(*seqs))
Concatenates several sequences.
lconcat
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lcat(seqs): """Concatenates the sequence of sequences.""" return list(cat(seqs))
Concatenates the sequence of sequences.
lcat
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def flatten(seq, follow=is_seqcont): """Flattens arbitrary nested sequence. Unpacks an item if follow(item) is truthy.""" for item in seq: if follow(item): yield from flatten(item, follow) else: yield item
Flattens arbitrary nested sequence. Unpacks an item if follow(item) is truthy.
flatten
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lflatten(seq, follow=is_seqcont): """Iterates over arbitrary nested sequence. Dives into when follow(item) is truthy.""" return list(flatten(seq, follow))
Iterates over arbitrary nested sequence. Dives into when follow(item) is truthy.
lflatten
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lmapcat(f, *seqs): """Maps given sequence(s) and concatenates the results.""" return lcat(map(f, *seqs))
Maps given sequence(s) and concatenates the results.
lmapcat
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def mapcat(f, *seqs): """Maps given sequence(s) and chains the results.""" return cat(map(f, *seqs))
Maps given sequence(s) and chains the results.
mapcat
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def interleave(*seqs): """Yields first item of each sequence, then second one and so on.""" return cat(zip(*seqs))
Yields first item of each sequence, then second one and so on.
interleave
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def interpose(sep, seq): """Yields items of the sequence alternating with sep.""" return drop(1, interleave(repeat(sep), seq))
Yields items of the sequence alternating with sep.
interpose
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def takewhile(pred, seq=EMPTY): """Yields sequence items until first predicate fail. Stops on first falsy value in one argument version.""" if seq is EMPTY: pred, seq = bool, pred else: pred = make_pred(pred) return _takewhile(pred, seq)
Yields sequence items until first predicate fail. Stops on first falsy value in one argument version.
takewhile
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def dropwhile(pred, seq=EMPTY): """Skips the start of the sequence passing pred (or just truthy), then iterates over the rest.""" if seq is EMPTY: pred, seq = bool, pred else: pred = make_pred(pred) return _dropwhile(pred, seq)
Skips the start of the sequence passing pred (or just truthy), then iterates over the rest.
dropwhile
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def ldistinct(seq, key=EMPTY): """Removes duplicates from sequences, preserves order.""" return list(distinct(seq, key))
Removes duplicates from sequences, preserves order.
ldistinct
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def distinct(seq, key=EMPTY): """Iterates over sequence skipping duplicates""" seen = set() # check if key is supplied out of loop for efficiency if key is EMPTY: for item in seq: if item not in seen: seen.add(item) yield item else: key = make_func(key) for item in seq: k = key(item) if k not in seen: seen.add(k) yield item
Iterates over sequence skipping duplicates
distinct
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def split(pred, seq): """Lazily splits items which pass the predicate from the ones that don't. Returns a pair (passed, failed) of respective iterators.""" pred = make_pred(pred) yes, no = deque(), deque() splitter = (yes.append(item) if pred(item) else no.append(item) for item in seq) def _split(q): while True: while q: yield q.popleft() try: next(splitter) except StopIteration: return return _split(yes), _split(no)
Lazily splits items which pass the predicate from the ones that don't. Returns a pair (passed, failed) of respective iterators.
split
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lsplit(pred, seq): """Splits items which pass the predicate from the ones that don't. Returns a pair (passed, failed) of respective lists.""" pred = make_pred(pred) yes, no = [], [] for item in seq: if pred(item): yes.append(item) else: no.append(item) return yes, no
Splits items which pass the predicate from the ones that don't. Returns a pair (passed, failed) of respective lists.
lsplit
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def split_at(n, seq): """Lazily splits the sequence at given position, returning a pair of iterators over its start and tail.""" a, b = tee(seq) return islice(a, n), islice(b, n, None)
Lazily splits the sequence at given position, returning a pair of iterators over its start and tail.
split_at
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lsplit_at(n, seq): """Splits the sequence at given position, returning a tuple of its start and tail.""" a, b = split_at(n, seq) return list(a), list(b)
Splits the sequence at given position, returning a tuple of its start and tail.
lsplit_at
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def split_by(pred, seq): """Lazily splits the start of the sequence, consisting of items passing pred, from the rest of it.""" a, b = tee(seq) return takewhile(pred, a), dropwhile(pred, b)
Lazily splits the start of the sequence, consisting of items passing pred, from the rest of it.
split_by
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lsplit_by(pred, seq): """Splits the start of the sequence, consisting of items passing pred, from the rest of it.""" a, b = split_by(pred, seq) return list(a), list(b)
Splits the start of the sequence, consisting of items passing pred, from the rest of it.
lsplit_by
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def group_by(f, seq): """Groups given sequence items into a mapping f(item) -> [item, ...].""" f = make_func(f) result = defaultdict(list) for item in seq: result[f(item)].append(item) return result
Groups given sequence items into a mapping f(item) -> [item, ...].
group_by
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def group_by_keys(get_keys, seq): """Groups items having multiple keys into a mapping key -> [item, ...]. Item might be repeated under several keys.""" get_keys = make_func(get_keys) result = defaultdict(list) for item in seq: for k in get_keys(item): result[k].append(item) return result
Groups items having multiple keys into a mapping key -> [item, ...]. Item might be repeated under several keys.
group_by_keys
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def group_values(seq): """Takes a sequence of (key, value) pairs and groups values by keys.""" result = defaultdict(list) for key, value in seq: result[key].append(value) return result
Takes a sequence of (key, value) pairs and groups values by keys.
group_values
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def count_by(f, seq): """Counts numbers of occurrences of values of f() on elements of given sequence.""" f = make_func(f) result = defaultdict(int) for item in seq: result[f(item)] += 1 return result
Counts numbers of occurrences of values of f() on elements of given sequence.
count_by
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def count_reps(seq): """Counts number occurrences of each value in the sequence.""" result = defaultdict(int) for item in seq: result[item] += 1 return result
Counts number occurrences of each value in the sequence.
count_reps
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def partition(n, step, seq=EMPTY): """Lazily partitions seq into parts of length n. Skips step items between parts if passed. Non-fitting tail is ignored.""" return _cut(True, n, step, seq)
Lazily partitions seq into parts of length n. Skips step items between parts if passed. Non-fitting tail is ignored.
partition
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lpartition(n, step, seq=EMPTY): """Partitions seq into parts of length n. Skips step items between parts if passed. Non-fitting tail is ignored.""" return list(partition(n, step, seq))
Partitions seq into parts of length n. Skips step items between parts if passed. Non-fitting tail is ignored.
lpartition
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def chunks(n, step, seq=EMPTY): """Lazily chunks seq into parts of length n or less. Skips step items between parts if passed.""" return _cut(False, n, step, seq)
Lazily chunks seq into parts of length n or less. Skips step items between parts if passed.
chunks
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause
def lchunks(n, step, seq=EMPTY): """Chunks seq into parts of length n or less. Skips step items between parts if passed.""" return list(chunks(n, step, seq))
Chunks seq into parts of length n or less. Skips step items between parts if passed.
lchunks
python
Suor/funcy
funcy/seqs.py
https://github.com/Suor/funcy/blob/master/funcy/seqs.py
BSD-3-Clause