Skip to main content

typeshi - a dead-simple TypedDict utility

Sometimes when working with Python typing we come across a situation when we need to quickly get a TypedDict object from an existing dict, and then maybe even make it into a self-contained declaration file -- typeshi does both of these things while exposing helpful function interfaces and utilities. You can get started right away by looking at the docstrings of the exposed functions listed below in your favorite code editor, or get a general feel for typeshi first with the examples that follow.

Documented functions of typeshi

  • typeddict_from_dict
  • typeddict_from_records
  • declaration_module_from_typeddict
  • save_declaration_module_from_json

Installation

$ pip install typeshi

Infer a schema from multiple records

typeddict_from_records accepts a nonempty iterable of dictionaries. It combines the observed fields into one record type.

from typeshi import declaration_module_from_typeddict, typeddict_from_records

rows = [{"id": 1, "label": "Draft"}, {"id": "external"}]
record = typeddict_from_records("Record", rows)
print(declaration_module_from_typeddict(record))

The generated Record has a required id: int | str and an optional label: NotRequired[str]. An explicit None adds a possible value type. Only an absent key makes a field optional by inference. Pass total=False to make every key optional.

Nested objects merge by field. For example, typeddict_from_dict("Page", {"rows": rows}) generates a Page with a rows: list[RowsItem] field. Empty lists use the element types observed in other samples at the same field, or Any if every list there is empty.

Generate and check a declaration

typeshi locale.json --name Locale -o schema.py
typeshi locale.json --name Locale -o schema.py --check

For a JSON object, --name names the root schema. For a nonempty JSON array of objects, it names the type of one record. The CLI and save_declaration_module_from_json infer literal values for eligible scalar fields by default. Use --no-literals for general types such as str and int.

Omit -o to print the declaration to standard output. You can also invoke the CLI with python -m typeshi.

--check reads the output file without modifying it and treats LF and CRLF line endings as equivalent.

Exit code Meaning
0 Generation succeeded, or the checked file is current.
1 The checked file is missing or stale.
2 The arguments, input, or file operation failed.

A quick example

typeshi exposes two main functions, typeddict_from_dict and declaration_module_from_typeddict. typeddict_from_dict is used to get a TypedDict from a dict instance at runtime, whereas declaration_module_from_typeddict generates the contents of a declaration module from a TypedDict. The most common usage of typeshi would be something like this:

# Let's say I have some JSON file that I load into my app at runtime,
# maybe it contains something like a locale or a config file...
# For the sake of this example let this be some sort of locale
with open(MY_JSON) as fp:
    my_dict = json.load(fp)

print(my_dict['greetings']['evening']['polite'])
# ^ I can *guess* that this is a string (and that it exists at all),
# but I'm lacking my Intellisense to be sure, let's change that
# I kind of wish I could develop easier with the help of type hints of my locale,
# this is where typeshi comes in:
import typeshi

# first, I'll generate my TypedDict
# since in this example I'm thinking of a locale, I'll name my TypedDict "Locale" as well as tell typeshi
# to convert applicable types into their typing.Literal counterparts, which will make my life easier while coding
td = typeshi.typeddict_from_dict(typeddict_name='Locale', original_dict=my_dict, literals_where_possible=True)

# Now my TypedDict is already generated, but it doesn't do much for me if it's just sitting in memory...
# I'll generate a declaration file so that I can import it and type hint my locale
declaration = typeshi.declaration_module_from_typeddict(td)
# okay, that's my declaration ready, now I'll just save it to a Python file of my choice...
with open('generated/locale_declaration.py', 'w+') as fp:
    fp.write(declaration)
# a generated typeshi declaration file will look something like this:

# generated/locale_declaration.py
from typing import TypedDict, Literal


class GreetingsEvening(TypedDict):
    polite: Literal['Good evening!']
    ...

class Greetings(TypedDict):
    evening: GreetingsEvening
    ...

class Locale(TypedDict):
    greetings: Greetings
    ...
# Okay! With that done, I can now import my TypedDict and use it to type hint my locale
from generated.locale_declaration import Locale

my_dict: Locale  # tell my editor that this is of my Locale type
my_dict['greetings']['evening']['polite']  # Literal['Good evening!']

Now, the locale example is obviously limiting, but the heart of typeshi, that being typeddict_from_dict, becomes very useful very quickly. It supports custom hooks for types and the naming of nested TypedDict classes, making it very easy to use and flexible -- everything is documented within docstrings.

It's worth noting the above example is significantly shortened by using the typeshi helper function save_declaration_module_from_json as follows:

from typeshi import save_declaration_module_from_json

save_declaration_module_from_json(toplevel_cls_name='Locale', json_path='my_json.json',
                                  declaration_path='generated/locale_declaration.py')

Contributing

typeshi is developed and maintained publicly on GitHub.

Metadata

Release files for typeshi 2.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for typeshi 2.1.0
File Size Uploaded Provenance Actions
typeshi-2.1.0.tar.gz 22.6 kB Without provenance Details for typeshi-2.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for typeshi 2.1.0
File Interpreter ABI Platform Actions
typeshi-2.1.0-py3-none-any.whl Python 3 none any Details for typeshi-2.1.0-py3-none-any.whl

Total release size: 39.1 kB

Release files / typeshi-2.1.0.tar.gz

Download URL typeshi-2.1.0.tar.gz
Size 22.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c26ce3619ee952816badda786fd0a891621b7fa0201228c253d2c8a1f5e3adc9
BLAKE2b-256 checksum
How to use checksums
714ba07c63d7a13c13e862a094cac83544667c9e4a488c0474b34d5ea778c127
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25

Release files / typeshi-2.1.0-py3-none-any.whl

Download URL typeshi-2.1.0-py3-none-any.whl
Size 16.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7367f368c628a0a54764ff30893611fcfddce6466d15432d163da2db84f1558d
BLAKE2b-256 checksum
How to use checksums
c6c396dff4e8b3d1ed5023679bca18219437cc7100d6b55df2aff96450ae8509
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25

Security for typeshi 2.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page