Collections¶
Unite¶
-
merge
(*colls)¶ Merges several collections of same type into one: dicts, sets, lists, tuples, iterators or strings. For dicts values of later dicts override values of former ones with same keys.
Can be used in variety of ways, but merging dicts is probably most common:
def utility(**options): defaults = {...} options = merge(defaults, options) ...
If you merge sequences and don’t need to preserve collection type, then use
concat()
orlconcat()
instead.
Transform and select¶
All functions in this section support Extended function semantics.
-
walk
(f, coll)¶ Returns a collection of same type as
coll
consisting of its elements mapped with the given function:walk(inc, {1, 2, 3}) # -> {2, 3, 4} walk(inc, (1, 2, 3)) # -> (2, 3, 4)
When walking dict,
(key, value)
pairs are mapped, i.e. this linesflip()
dict:swap = lambda (k, v): (v, k) walk(swap, {1: 10, 2: 20})
walk()
works with strings too:walk(lambda x: x * 2, 'ABC') # -> 'AABBCC' walk(compose(str, ord), 'ABC') # -> '656667'
One should use
map()
when there is no need to preserve collection type.
-
walk_keys
(f, coll)¶ Walks keys of
coll
, mapping them with the given function. Works with mappings and collections of pairs:walk_keys(str.upper, {'a': 1, 'b': 2}) # {'A': 1, 'B': 2} walk_keys(int, json.loads(some_dict)) # restore key type lost in translation
Important to note that it preserves collection type whenever this is simple
dict
,defaultdict
,OrderedDict
or any other mapping class or a collection of pairs.
-
walk_values
(f, coll)¶ Walks values of
coll
, mapping them with the given function. Works with mappings and collections of pairs.Common use is to process values somehow:
clean_values = walk_values(int, form_values) sorted_groups = walk_values(sorted, groups)
Hint: you can use
partial(sorted, key=...)
instead ofsorted()
to sort in non-default way.Note that
walk_values()
has special handling fordefaultdicts
. It constructs new one with values mapped the same as for ordinary dict, but a default factory of newdefaultdict
would be a composition off
and old default factory:d = defaultdict(lambda: 'default', a='hi', b='bye') walk_values(str.upper, d) # -> defaultdict(lambda: 'DEFAULT', a='HI', b='BYE')
-
select
(pred, coll)¶ Filters elements of
coll
bypred
constructing a collection of same type. When filtering a dictpred
receives(key, value)
pairs. Seeselect_keys()
andselect_values()
to filter it by keys or values respectively:select(even, {1, 2, 3, 10, 20}) # -> {2, 10, 20} select(lambda (k, v): k == v, {1: 1, 2: 3}) # -> {1: 1}
-
select_keys
(pred, coll)¶ Select part of a dict or a collection of pairs with keys passing the given predicate.
This way a public part of instance attributes dictionary could be selected:
is_public = complement(re_tester('^_')) public = select_keys(is_public, instance.__dict__)
-
select_values
(pred, coll)¶ Select part of a dict or a collection of pairs with values passing the given predicate:
# Leave only str values select_values(isa(str), values) # Construct a dict of methods select_values(inspect.isfunction, cls.__dict__)
-
compact
(coll)¶ Removes falsy values from given collection. When compacting a dict all keys with falsy values are removed.
Extract integer data from request:
compact(walk_values(silent(int), request_dict))
Dict utils¶
-
merge_with
(f, *dicts)¶ -
join_with
(f, dicts)¶ Merge several dicts combining values for same key with given function:
merge_with(list, {1: 1}, {1: 10, 2: 2}) # -> {1: [1, 10], 2: [2]} merge_with(sum, {1: 1}, {1: 10, 2: 2}) # -> {1: 11, 2: 2} join_with(first, ({n % 3: n} for n in range(100, 110))) # -> {0: 102, 1: 100, 2: 101}
-
zipdict
(keys, vals)¶ Returns a dict with the
keys
mapped to the correspondingvals
. Stops pairing on shorter sequence end:zipdict('abcd', range(4)) # -> {'a': 0, 'b': 1, 'c': 2, 'd': 3} zipdict('abc', count()) # -> {'a': 0, 'b': 1, 'c': 2}
-
flip
(mapping)¶ Flip passed dict swapping its keys and values. Also works for sequences of pairs. Preserves collection type:
flip(OrderedDict(['aA', 'bB'])) # -> OrderedDict([('A', 'a'), ('B', 'b')])
-
project
(mapping, keys)¶ Returns a dict containing only those entries in
mapping
whose key is inkeys
.Most useful to shrink some common data or options to predefined subset. One particular case is constructing a dict of used variables:
merge(project(__builtins__, names), project(globals(), names))
-
omit
(mapping, keys)¶ Returns a copy of
mapping
withkeys
omitted. Preserves collection type:omit({'a': 1, 'b': 2, 'c': 3}, 'ac') # -> {'b': 2}
-
zip_values
(*dicts)¶ Yields tuples of corresponding values of given dicts. Skips any keys not present in all of the dicts. Comes in handy when comparing two or more dicts:
error = sum((x - y) ** 2 for x, y in zip_values(result, reference))
-
zip_dicts
(*dicts)¶ Yields tuples like
key, (value1, value2, ...)
for each common key of all given dicts. A neat way to process several dicts at once:changed_items = [id for id, (new, old) in zip_dicts(items, old_items) if abs(new - old) >= PRECISION] lines = {id: cnt * price for id, (cnt, price) in zip_dicts(amounts, prices)}
See also
zip_values()
.
-
get_in
(coll, path, default=None)¶ Returns a value corresponding to
path
in nested collection:get_in({"a": {"b": 42}}, ["a", "b"]) # -> 42 get_in({"a": {"b": 42}}, ["c"], "foo") # -> "foo"
-
set_in
(coll, path, value)¶ Creates a nested collection with the
value
set at specifiedpath
. Original collection is not changed:set_in({"a": {"b": 42}}, ["a", "b"], 10) # -> {"a": {"b": 10}} set_in({"a": {"b": 42}}, ["a", "c"], 10) # -> {"a": {"b": 42, "c": 10}}
-
update_in
(coll, path, update, default=None)¶ Creates a nested collection with a value at specified
path
updated:update_in({"a": {}}, ["a", "cnt"], inc, default=0) # -> {"a": {"cnt": 1}}
-
has_path
(coll, path)¶ Checks if path exists in the given nested collection:
has_path({"a": {"b": 42}}, ["a", "b"]) # -> True has_path({"a": {"b": 42}}, ["c"]) # -> False has_path({"a": [1, 2]}, ["a", 0]) # -> True
Data manipulation¶
-
where
(mappings, **cond)¶ -
lwhere
(mappings, **cond)¶ Looks through each value in given sequence of dicts and returns an iterator or a list of all the dicts that contain all key-value pairs in
cond
:lwhere(plays, author="Shakespeare", year=1611) # => [{"title": "Cymbeline", "author": "Shakespeare", "year": 1611}, # {"title": "The Tempest", "author": "Shakespeare", "year": 1611}]
Iterator version could be used for efficiency or when you don’t need the whole list. E.g. you are looking for the first match:
first(where(plays, author="Shakespeare")) # => {"title": "The Two Gentlemen of Verona", ...}
-
pluck
(key, mappings)¶ -
lpluck
(key, mappings)¶ Returns an iterator or a list of values for
key
in each mapping in the given sequence. Essentially a shortcut for:map(operator.itemgetter(key), mappings)
-
pluck_attr
(attr, objects)¶ -
lpluck_attr
(attr, objects)¶ Returns an iterator or a list of values for
attr
in each object in the given sequence. Essentially a shortcut for:map(operator.attrgetter(attr), objects)
Useful when dealing with collections of ORM objects:
users = User.query.all() ids = lpluck_attr('id', users)
Content tests¶
-
is_distinct
(coll, key=identity)¶ Checks if all elements in the collection are different:
assert is_distinct(field_names), "All fields should be named differently"
Uses
key
to differentiate values. This way one can check if all first letters ofwords
are different:is_distinct(words, key=0)
-
all
([pred, ]seq)¶ Checks if
pred
holds for every element in aseq
. Ifpred
is omitted checks if all elements ofseq
are truthy – same as in built-inall()
:they_are_ints = all(is_instance(n, int) for n in seq) they_are_even = all(even, seq)
Note that, first example could be rewritten using
isa()
like this:they_are_ints = all(isa(int), seq)
-
any
([pred, ]seq)¶ Returns
True
ifpred
holds for any item in given sequence. Ifpred
is omitted checks if any element ofseq
is truthy.Check if there is a needle in haystack, using extended predicate semantics:
any(r'needle', haystack_strings)
-
none
([pred, ]seq)¶ Checks if none of items in given sequence pass
pred
or is truthy ifpred
is omitted.Just a stylish way to write
not any(...)
:assert none(' ' in name for name in names), "Spaces in names not allowed" # Or same using extended predicate semantics assert none(' ', names), "..."
-
one
([pred, ]seq)¶ Returns true if exactly one of items in
seq
passespred
. Cheks for truthiness ifpred
is omitted.
-
some
([pred, ]seq)¶ Finds first item in
seq
passingpred
or first that is true ifpred
is omitted.
Low-level helpers¶
-
empty
(coll)¶ Returns an empty collection of the same type as
coll
.
-
iteritems
(coll)¶ Returns an iterator of items of a
coll
. This meanskey, value
pairs for any dictionaries:list(iteritems({1, 2, 42})) # -> [1, 42, 2] list(iteritems({'a': 1})) # -> [('a', 1)]
-
itervalues
(coll)¶ Returns an iterator of values of a
coll
. This means values for any dictionaries and just elements for other collections:list(itervalues({1, 2, 42})) # -> [1, 42, 2] list(itervalues({'a': 1})) # -> [1]
Makes infinite iterator of values:
start, start + step, start + 2*step, ...
Cycles passed sequence indefinitely
yielding its elements one by one.
Makes an iterator yielding item for n times
or indefinitely if n is omitted.
Takes a function of no args, presumably with side effects,
and returns an infinite (or length n) iterator of calls to it.
Returns an infinite iterator of
x, f(x), f(f(x)), ...
Lists all matches of regex in s.
Iterates over matches of regex in s.
Returns the first item in the sequence.
Returns
None
if the sequence is empty.
Returns second item in the sequence.
Returns
None
if there are less than two items in it.
Returns the last item in the sequence.
Returns
None
if the sequence is empty.
Returns nth item in the sequence
or
None
if no such item exists.
Finds first item in seq passing pred
or first that is true if pred is omitted.
Returns a list of first n items in the sequence,
or all items if there are fewer than n.
Skips first n items in the sequence,
yields the rest.
Skips first item in the sequence, yields the rest.
Yields all elements of the sequence but last.
Yields seq items as long as they pass pred.
Skips elements of seq while pred passes
and then yields the rest.
lsplit_at(n, seq)
Splits the sequence at given position,
returning a tuple of its start and tail.
lsplit_by(pred, seq)
Splits the start of the sequence,
consisting of items passing pred,
from the rest of it.
lmap(f, *seqs)
Extended versions of map() and list(map())
lmapcat(f, *seqs)
Maps given sequence(s) and concatenates the results.
lkeep([f, ]*seqs)
Maps seq with f and filters out falsy results.
Simply removes falsy values in one argument version.
lpluck(key, mappings)
Yields or lists values for key in each mapping.
lpluck_attr(attr, objects)
Yields or lists values of attr of each object.
linvoke(objects, name, *args, **kwargs)
Yields or lists results of the given method call
for each object in objects.
Wrap a property accessors with ctx.
lfilter(pred, seq)
Extended versions of filter() and list(filter()).
lremove(pred, seq)
Removes items from seq passing given predicate.
ldistinct(seq, key=identity)
Removes items having same key from seq.
Preserves order.
lwhere(mappings, **cond)
Selects mappings containing all pairs in cond.
lwithout(seq, *items)
Returns sequence without items,
preserves order.
lcat(seqs)
Concatenates passed sequences.
lconcat(*seqs)
Concatenates several sequences.
lflatten(seq, follow=is_seqcont)
Flattens arbitrary nested sequence,
dives into when
follow(item)
is truthy.
Yields first item of each sequence,
then second one and so on.
Yields items of seq separated by sep.
List version of zip()
lchunks(n, [step, ]seq)
Chunks seq into parts of length n or less.
Skips step items between chunks.
lpartition(n, [step, ]seq)
Partitions seq into parts of length n.
Skips step items between parts.
Non-fitting tail is ignored.
lpartition_by(f, seq)
Partition seq into continuous chunks
with constant value of f.
lsplit(pred, seq)
Splits seq items which pass pred
from the ones that don't.
Counts numbers of occurrences of values of f
on elements of seq.
Counts repetitions of each value in seq.
Groups items of seq by
f(item)
.
Groups elements of seq by multiple keys.
Groups values of
(key, value)
pairs by keys.
Consumes the given iterator and returns its length.
lreductions(f, seq[, acc])
Constructs intermediate reductions of seq by f.
lsums(seq[, acc])
Returns a sequence of partial sums of seq.
Checks if all items in seq pass pred.
Checks if any item in seq passes pred.
Checks if none of the items in seq pass pred.
Checks if exactly one item in seq passes pred.
Yields all pairs of neighboring items in seq.
Yields each item from seq with the one preceding it.
Yields each item from seq with the next one.
Yields tuples of corresponding values of given dicts.
Yields tuples like
(key, val1, val2, ...)
for each common key in all given dicts.
ltree_leaves(root, follow=is_seqcont, children=iter)
Lists or iterates over tree leaves.
ltree_nodes(root, follow=is_seqcont, children=iter)
Lists or iterates over tree nodes.
Merges several collections of same type into one:
dicts, sets, lists, tuples, iterators or strings
For dicts later values take precedence.
Merges several dicts combining values with given function.
Joins several collections of same type into one.
Same as merge() but accepts sequence of collections.
Joins several dicts combining values with given function.
Maps coll with f, but preserves collection type.
Walks keys of coll, mapping them with f.
Works with dicts and collections of pairs.
Walks values of coll, mapping them with f.
Works with dicts and collections of pairs.
Filters elements of coll by pred
constructing a collection of same type.
Select part of coll with keys passing pred.
Works with dicts and collections of pairs.
Select part of coll with values passing pred.
Works with dicts and collections of pairs.
Removes falsy values from given collection.
These are targeted specifically at them.
Flip passed dict swapping its keys and values.
Creates a dict with keys mapped to the corresponding vals.
Yields values of the given collection.
Yields
(key, value)
pairs of the given collection.
Leaves only given keys in mapping.
Removes given keys from mapping.
Returns an empty collection of the same type as coll.
Returns a value at path in the given nested collection.
Creates a copy of coll with the value set at path.
Creates a copy of coll with a value updated at path.
Tests whether path exists in a nested coll.
Returns its argument.
Creates a function accepting any args, but always returning x.
Like partial() but returns a real function.
Returns partial application of func.
Partially applies last arguments to func.
Creates a function, which conditionally applies action or default.
Creates a function calling its argument with passed arguments.
Creates a function finding regex in passed string.
Creates a predicate testing passed strings with regex.
Constructs a complementary predicate.
Creates a version of func returning its partial applications
until sufficient arguments are passed.
Curries func into a chain of one argument functions.
Arguments are passed from left to right.
Curries func from right to left.
Composes passed functions.
Composes fs, calling them from left to right.
ljuxt(*fs)
Constructs a juxtaposition of the given functions.
Result returns a list or an iterator of results of fs.
Constructs a predicate,
which holds when all fs hold.
Constructs a predicate,
which holds when any of fs holds.
Constructs a predicate,
which holds when none of fs hold.
Constructs a predicate,
which holds when exactly one of fs holds.
Constructs a function, which calls fs one by one
and returns first truthy result.
Checks if all elements in the collection are different.
Creates a function checking if its argument
is of any of given types.
Checks whether value is an iterator.
Checks whether value is a mapping.
Checks whether value is a set.
Checks whether value is a list.
Checks whether value is a tuple.
Checks whether value is a
Sequence
.
Checks whether value is a mapping.
Checks whether value is a list or a tuple,
which are both sequences and collections.
Checks whether value is a list, a tuple or an iterator,
which are both sequences and containers.
Checks whether value is iterable.
Transforms a flat wrapper into a decorator.
An utility to pass function metadata
from wrapped function to a wrapper.
Get the object wrapped by func.
Let function execute only once.
Noop all subsequent calls.
Call function only once for every combination
of the given arguments.
Call function only once for every combination
of values of its arguments.
Transforms a generator into list returning function.
Joins decorated function results with sep.
Post processes decorated function result with func.
Only runs a decorated function once per period.
Turn context manager into a decorator.
A noop context manager.
Tries decorated function up to tries times.
Retries only on specified errors.
Alters function to ignore all exceptions.
Alters function to ignore errors,
returning default instead.
The context manager suppressing errors in its block.
If function fails to complete fails times in a row,
calls to it will be blocked for timeout seconds.
Tries several approaches until one works.
Each approach has a form of
(callable, errors)
.
Constructs function that raises the given exception
with given arguments on any invocation.
Intercepts errors and reraises them as into exception.
Prints x and then returns it.
@print_calls(errors=True, stack=True)
Logs or prints all function calls,
including arguments, results and raised exceptions.
@print_enters
Logs or prints on each enter to a function.
@print_exits(errors=True, stack=True)
Logs or prints on each exit from a function.
@print_errors(label=None, stack=True)
Logs or prints all errors within a function or block.
@print_durations(label=None)
Times each function call or block execution.
print_iter_durations(seq, label=None)
Times processing of each item in seq.
Memoizes a decorated function results.
Caches a function results for timeout seconds.
Creates a property caching its result.
Creates a read-only property caching its result.
Creates a cached function with prefilled memory.
Creates a cached function with prefilled memory.
Ignores memory misses, returning
None
.
Matches regex against the given string,
returns the match in the simplest possible form.
Tests whether regex matches against s.
Cuts prefix from given string if it's present.
Cuts suffix from given string if it's present.
Joins the given sequence with sep.
Forces stringification of seq items.
Monkey-patches class or module.
A base class that prevents functions turning into methods.
Creates an object setting itself up on first use.
Checks if x is None.
Checks if x is not None.
Increments its argument by 1.
Decrements its argument by 1.
Checks if x is even.
Checks if x is odd.