Skip to main content

Safely accessing deeply nested values

Project description

th

License Codecov PyPI Python Version

Overview

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

TypeError: 'NoneType' object is not subscriptable

becomes:

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

th.TypeError: _.body['users'][0]['name']
              ^^^^^^^^^^^^^^^ inappropriate type (NoneType)

Installation

pip3 install th

Usage

Default

total = get(response, _.body["total"], default=0)
# no exception

Verbose

user = get(response.body, _["users"][4]["id"], verbose=True)

th.IndexError: _['users'][4]['id']
                          ^ out of range
where _ is <class 'dict'>:
{'users': [{'id': 1, 'name': 'Bob'},
           {'id': 2, 'name': 'Alice'},
           {'id': 3, 'name': 'Eve'}]}

Examples

AttributeError: 'Response' object has no attribute 'body'
# ->
th.AttributeError: _.body['users'][0]['name']
                     ^^^^ does not exist
IndexError: list index out of range
# ->
th.IndexError: _.body['users'][0]['name']
                               ^ out of range
KeyError: 'users'
# ->
th.KeyError: _.body['users'][0]['name']
                    ^^^^^^^ does not exist
TypeError: list indices must be integers or slices, not NoneType
# -> 
th.TypeError: _.body['users'][None]['name']
                              ^^^^ inappropriate type (NoneType)
TypeError: 'NoneType' object is not subscriptable
# ->
th.TypeError: _.body['users'][0]['name']
              ^^^^^^^^^^^^^^^ inappropriate type (NoneType)

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.1.1.tar.gz (4.2 kB view hashes)

Uploaded Source

Built Distribution

th-0.1.1-py3-none-any.whl (8.4 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