Inspect nested data structures.
Project description
Handpick
Handpick is a tool to traverse nested data structures and pick all objects that meet certain criteria.
Installation
pip install handpick
Quick introduction
The pick function
The pick generator function is the library’s main component. It performs the recursive traversal of a (presumably nested) data structure and applies the picking criteria provided in the form of a predicate function (see below for various examples). Picked objects are retrieved lazily by an iterator.
Simple predicate functions
The predicate function is passed to pick as the second positional argument. In simple cases, you can use a lambda function as a predicate. For example:
from handpick import pick
data = [[1, 'Py'], [-2, ['', 3.0]], -4]
non_empty_strings = pick(data, lambda s: isinstance(s, str) and s)
>>> list(non_empty_strings)
['Py']
Non-callable predicates
If predicate is not callable, equality will be used as the picking criteria. For example:
from handpick import pick
data = [1, [1.0, [2, 1.]], [{'1': 1}, [3]]]
ones = pick(data, 1) # equivalent to pick(data, lambda n: n == 1)
>>> list(ones)
[1, 1.0, 1.0, 1]
Handling dictionary keys
When inspecting dictionaries or other mappings, you can configure whether or not pick will inspect dictionary keys using the dict_keys keyword argument. Default is False, which means only dictionary values are inspected. For example:
from handpick import pick
data = {'foo': {'name': 'foo'}, 'bar': {'name': 'bar'}}
default = pick(data, lambda s: 'a' in s)
keys_included = pick(data, lambda s: 'a' in s, dict_keys=True)
>>> list(default)
['bar']
>>> list(keys_included)
['name', 'bar', 'name', 'bar']
Predicates
The predicate decorator
The predicate decorator wraps a function in an object that can be combined with other predicates using the operators & (and) and | (or), as well as negated using the operator ~ (not).
Combining predicates
For example:
from handpick import pick, predicate
@predicate
def is_int(n):
return isinstance(n, int)
@predicate
def is_even(n):
return n % 2 == 0
data = [[4, [5.0, 1], 3.0], [[15, []], {17: [7, [8], 0]}]]
# compound predicate
non_even_int = is_int & ~is_even
odd_integers = pick(data, non_even_int)
>>> list(odd_integers)
[1, 15, 7]
Combining predicates with functions
In addition, the & and | operations are supported between predicates and regular undecorated functions. For example:
from handpick import pick, predicate
@predicate
def is_list(obj):
return isinstance(obj, list)
data = [('1', [2]), {('x',): [(3, [4]), '5']}, ['x', ['6']], {7: ('x',)}]
# compound predicate
short_list = (lambda obj: len(obj) < 2) & is_list
short_lists = pick(data, short_list)
>>> list(short_lists)
[[2], [4], ['6']]
Suppressing errors
One important thing to note: when the predicate’s underlying function raises an exception, the exception is suppressed and instead the call to the predicate returns False. In other words, it is assumed that the object in question does not meet the picking criteria. For example:
from handpick import pick, predicate
@predicate
def above_zero(n):
return n > 0
>>> above_zero(1)
True
>>> above_zero('a')
False
>>> positive_numbers = pick([[1, 'Py', -2], [None, 3.0]], above_zero)
>>> list(positive_numbers)
[1, 3.0]
In the example above, several lists and strings were internally compared to 0 but no TypeError propagated up to the code that called above_zero.
Predicate factories
The is_type and not_type functions can be used to create predicates based on an object’s type. For example:
from handpick import pick, is_type, not_type
data = [[1.0, [2, True]], [False, [3]], ['4', {5, True}]]
strictly_integers = pick(data, is_type(int) & not_type(bool))
>>> list(strictly_integers)
[2, 3, 5]
Built-in predicates
Handpick provides some predefined predicates to be used in common scenarios. For example:
from handpick import pick, IS_CONTAINER
data = [[], [0], [['1'], b'2']]
# pick only objects that are not containers of other objects
only_values = pick(data, ~IS_CONTAINER)
>>> list(only_values)
[0, '1', b'2']
Note: Despite being iterable, strings and bytes-like objects are not treated as containers of other objects by IS_CONTAINER.
Useful functions
The values_for_key function
When inspecting data structures that contain dictionaries or other mappings, you can use this function to retrieve values associated with a specific key, regardless of the nested depth in which these values are stored. Values are retrieved lazily by an iterator. For example:
from handpick import values_for_key
data = {'node_id': 4,
'child_nodes': [{'node_id': 8,
'child_nodes': [{'node_id': 16}]},
{'node_id': 9}]}
node_ids = values_for_key(data, key='node_id')
>>> list(node_ids)
[4, 8, 16, 9]
The max_depth function
This function returns the maximum nested depth of a data structure. For example:
from handpick import max_depth
nested_list = [0, [1, [2]]]
nested_dict = {0: {1: {2: {3: {4: 4}}}}}
>>> max_depth(nested_list)
2
>>> max_depth(nested_dict)
4
Note: Just like non-empty containers, empty containers constitute another level of nested depth. For example:
>>> max_depth([0, [1, []]])
2
Recipes
Flattening nested data
For example:
from handpick import pick, not_type
data = [[], [0], [[[], 1], [2, [3, [4]], []], [5]]]
flat_data = pick(data, not_type(list))
>>> list(flat_data)
[0, 1, 2, 3, 4, 5]
API reference
- handpick.pick(data, predicate, containers=True, dict_keys=False, strings=False, bytes_like=False)
Pick objects from data based on predicate.
Traverse data recursively and yield all objects for which predicate(obj) is True or truthy.
data should be an iterable container.
predicate should be a callable taking one argument and returning a Boolean value. If predicate is not callable, equality will be used as the picking criteria, i.e. objects for which obj == predicate will be yielded.
By default, containers of other objects are yielded just like any other objects. To exclude containers, set containers to False.
When traversing a mapping, only its values are inspected by default. If dict_keys is set to True, both keys and values of the mapping are inspected.
By default, strings are not treated as containers of other objects and therefore not iterated by the recursive algorithm. This can be changed by setting strings to True. Strings of length 1 are never iterated.
By default, bytes-like sequences (bytes and bytearrays) are not treated as containers of other objects and therefore not iterated by the recursive algorithm. This can be changed by setting bytes_like to True.
- @handpick.predicate(func)
Decorator wrapping a function in a predicate object.
The decorated function can be combined with other predicates using the operators & (and) and | (or), as well as negated using the operator ~ (not).
Predicate objects are intended to be used as the predicate argument to the pick function.
- handpick.is_type(type_or_types)
Predicate factory. Return a predicate that returns True if object is an instance of specified type(s).
type_or_types must be a type or tuple of types.
- handpick.not_type(type_or_types)
Predicate factory. Return a predicate that returns True if object is not an instance of specified type(s).
type_or_types must be a type or tuple of types.
- handpick.IS_CONTAINER
Predicate that returns True for iterable containers of other objects. Strings and bytes-like objects are not treated as containers.
- handpick.IS_MAPPING
Predicate that returns True for dictionaries and other mappings.
- handpick.values_for_key(data, key)
Pick values associated with a specific key.
Traverse data recursively and yield a sequence of dictionary values that are mapped to a dictionary key key.
- handpick.max_depth(data)
Return maximum nested depth of data.
data should be an iterable container. Depth is counted from zero, i.e. the direct elements of data are in depth 0.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.