Skip to main content

A small Python library that provides a ruby-like dig function for accessing nested members of dictionaries (and "dict-like" structures, which support the __getitem__ method).

Project description

typed-dig

A small Python library that provides a ruby-like dig function for accessing nested members of dictionaries (and "dict-like" structures, which support the __getitem__ method).

Why?

This library was created based on a function written to simplify interacting with a specific API. That API was, effectively, a wrapper around a deeply nested JSON API, returning dicts of unkown type that we had to check manually to satisfy our type checker.

After a discussion with a friend (who's more familiar with Ruby than I am), the Ruby dig function came up, and I spent half a day at work writing what would soon become this library.

This function allows you to take the nested dictionaries returned by such APIs and access the keys you care about, while ensuring the value is correct, with significantly less overhead than manual validation (and fewer # type: ignore comments!).

Before:

api_response = get_api_data()

if not (
  "response" in api_response
  and "body" in api_response["response"]
  and isinstance(api_response["response"]["body"], dict)
):
  raise Exception(f"Invalid API response: {api_response}")

response_data: dict = api_response["response"]["body"]  # type: ignore # this was validated maually
do_something_with_response(response_data)

After:

from typed_dig import dig

api_response = get_api_data()

try:
    response_data = dig(api_response, "response", "body", expected_type=dict)
except KeyError | ValueError:
    raise Exception(f"Invalid API response: {api_response}")
do_something_with_response(response_data)

This is a fairly minor improvement, but it makes for much cleaner code, and reduces the likelihood of a logic error when repeating similar (but different) checks across your codebase.

Type Checker (LSP) Compatibility

This library should be broadly compatible with Python type checkers, provided you provide an expected_type when calling the dig function. This is accomplished by defining a TypeVar that's bound to both the expected_type parameter and used as the return type of the function. When not provided, it defaults to object, which may have different beahaviors in different type checkers. Of course, if you're not using a type checker, you might still find this function useful--and you won't have any reason to pass an expected_type!

This library has been tested with the following type checkers:

  • pyright
  • pylance
  • pyanalyze

Additionally, we've tested with both pyright and pylance as LSPs, and behavior between them is identical: when expected_type is provided, they recognize variables assigned by dig as being that type, and when left off they only provide object.

Usage

Import the dig function and call it with a dictionary and a list of keys:

from typed_dig import dig

example_dict = {
    "a": {
        "b": {
            "c": 1337,
            "d": "l33t"
        }
    }
}

dig(example_dict, "a", "b", "c", expected_type=int) # returns 1337
dig(example_dict, "a", "b", "d", expected_type=str) # returns "l33t"
dig(example_dict, "a", "b", "e")                    # raises KeyError
dig(example_dict, "a", "b", "c", expected_type=str) # raises ValueError

Acknowledgements

Much of this project's structure is from python-boilerplate.

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

typed_dig-0.1.0.tar.gz (4.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

typed_dig-0.1.0-py3-none-any.whl (5.2 kB view details)

Uploaded Python 3

File details

Details for the file typed_dig-0.1.0.tar.gz.

File metadata

  • Download URL: typed_dig-0.1.0.tar.gz
  • Upload date:
  • Size: 4.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.4 Linux/6.10.0-gentoo-x86_64.vhz

File hashes

Hashes for typed_dig-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cdae05c730c04d8eb73b05c7aa2b9272131deb45f9efdb0ba1de12ac7342d63c
MD5 eb74ed463d70172741c57be3ec582354
BLAKE2b-256 90dfe6765f607f812c4659bb120a3ea4377a7f94c097adc8e84f2d1e5c3d467a

See more details on using hashes here.

File details

Details for the file typed_dig-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: typed_dig-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 5.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.4 Linux/6.10.0-gentoo-x86_64.vhz

File hashes

Hashes for typed_dig-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 47b0ed69eff124cbad96605355695bbf8b2719a643ef39f5e5c4d227bdd39aa4
MD5 b149a3404b38d9779889d9c9a23c1a7c
BLAKE2b-256 1cd79e141ac3e99a8ecf8e3aed67a67dca812ac5d516b4fba18c8bb2978d3b38

See more details on using hashes here.

Supported by

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