Safely accessing deeply nested values


License
Apache-2.0
Install
pip install th==0.3.2

Documentation

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)