Skip to main content

Safely accessing deeply nested values

Project description

th

Codecov PyPI PyPI - Downloads 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.

Files for th, version 0.3.0
Filename, size File type Python version Upload date Hashes
Filename, size th-0.3.0-py3-none-any.whl (9.6 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size th-0.3.0.tar.gz (9.0 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page