Skip to main content

Safely accessing deeply nested values

Project description

th

Codecov PyPI PyPI - Downloads Python Version

Introduction

th is a Python library that provides a convenient way to access nested attributes and items in complex data structures, with clear and informative error messages when something goes wrong.

When working with deeply nested data structures like JSON responses or complex objects, accessing nested attributes or items can lead to confusing and uninformative error messages when a part of the path doesn't exist or is of the wrong type.

th simplifies this by allowing you to specify the path using a special path holder object _, and provides detailed error messages indicating exactly where the problem occurred.

Installation

You can install th using pip:

pip install th

Usage

Basic Usage

Suppose you have a complex response object and you want to access a nested value:

username = response.body["users"][0]["name"]

If any part of this path doesn't exist or is None, you might get a TypeError or AttributeError with a less-than-helpful message.

With th, you can do:

from th import get, _

username = get(response, _.body["users"][0]["name"])

If everything goes well, username will be set to the desired value. If there's an error, th will raise an informative exception showing exactly where the problem occurred in the path.

Providing a Default Value

If you want to provide a default value in case the path doesn't exist or is of the wrong type, you can use the default parameter:

username = get(response, _.body["users"][0]["name"], default="Unknown")

If one of the parts of the path doesn't exist or is of the wrong type, username will be set to "Unknown".

Verbose Mode

If you need more detailed information about the error, you can enable verbose mode:

username = get(response, _.body["users"][0]["name"], verbose=True)

Suppose response.body["users"] is None, you would get an error message like:

th.TypeError: _.body['users'][0]['name']
              ^^^^^^^^^^^^^^^ inappropriate type (NoneType)
where _ is <class 'Response'>:
Response({'total': 3, 'users': None})

This includes additional debug information in the error message, such as the type and value of the object at the point of failure.

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

th-0.4.0.tar.gz (13.8 kB view hashes)

Uploaded Source

Built Distribution

th-0.4.0-py3-none-any.whl (12.5 kB view hashes)

Uploaded Python 3

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