Skip to main content

Lookup nested data structures

Project description

PyPI Versions Travis Codecov Black

lookuper makes it easy to lookup a target in nested data structures. A lookup can return the values matching a target as a string or, equivalently, as a list:

>>> from lookuper import lookup
>>> list(lookup('a.0.b', {'a': [{'b': 1}]}))
[1]
>>> list(lookup(['a', 0, 'b'], {'a': [{'b': 1}]}))
[1]

As a string, a target can contain stars (*) to match anything and globstars (**) to match anything recursively:

>>> list(lookup('a.*', {'a': {'b': 1, 'B': 2}}))
[1, 2]
>>> list(lookup('**.b', [{'b': 1}, {'a': {'b': 2}}]))
[1, 2]

As a list, the same matching can be achieved with STAR and GLOBSTAR respectively. Additionally, a target can also contain regular expressions and functions:

>>> from lookuper import STAR
>>> list(lookup(['a', STAR], {'a': {'b': 1, 'B': 2}}))
[1, 2]
>>> import re
>>> list(lookup(['a', re.compile(r'[a-z]')], {'a': {'b': 1, 'B': 2}}))
[1]
>>> from lookuper import match
>>> list(lookup(['a', match(str.islower)], {'a': {'b': 1, 'B': 2}}))
[1]

Recipes

lookuper can be combined with other libraries like more-itertools to return only one value:

>>> from more_itertools import only
>>> def lookup1(target, data, **kwargs):
...     return only(lookup(target, data), **kwargs)
>>> lookup1('a', {})
>>> lookup1('a', {'a': 1})
1
>>> lookup1('*', {'a': 1, 'b': 2})
Traceback (most recent call last):
...
ValueError: Expected exactly one item in iterable, but got 1, 2, and perhaps more.

Extensions

By default, lookuper only supports nested data structures like mappings, sequences and sets. It can extended to support other types:

>>> from lookuper import lookup_data
>>> func = lookup_data.register(object, lambda data: (
...     (name, getattr(data, name)) for name in dir(data)
... ))
>>> list(lookup('__class__.__doc__', object()))
['The most base type']

Project information

lookuper is released under the MIT license, the code on GitHub, and the latest release on PyPI.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lookuper-0.3.1.tar.gz (6.7 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page