Useful Types
useful-types is a Python library offering a collection of common type aliases and protocols to reduce boilerplate in projects. It aims to provide frequently used type definitions, such as JSON-related types. The library's types are not specially handled by type checkers, and users are encouraged to vendor them if they wish to avoid a direct dependency. It is currently at version 0.2.1 and maintains an active development cadence with occasional updates to type definitions.
Warnings
- gotcha The library explicitly states that its types are not specially handled by type checkers and encourages users to 'vendor' (copy) them into their own projects if they prefer not to take on a direct dependency. This is a design philosophy choice, not a technical limitation.
- gotcha The library guarantees support on `mypy 1.4` and `pyright 1.1.314` or higher. Using older versions of these type checkers or alternative type checkers (e.g., Pyright, Pylance, etc.) might lead to unexpected type-checking behavior or errors, as the types might rely on newer type checker features.
Install
-
pip install useful-types
Imports
- JSONDict
from useful_types import JSONDict
- JSONType
from useful_types import JSONType
- LiteralString
from useful_types.typing_extensions_extended import LiteralString
Quickstart
from useful_types import JSONDict, JSONType
def process_json_data(data: JSONType) -> JSONType:
if isinstance(data, dict):
if 'id' in data and isinstance(data['id'], str):
print(f"Processing record with ID: {data['id']}")
return {k: v for k, v in data.items() if k != 'private_field'}
elif isinstance(data, list):
return [process_json_data(item) for item in data]
return data
example_dict: JSONDict = {
"name": "Alice",
"age": 30,
"isStudent": False,
"courses": ["Math", "Science"],
"address": {"street": "123 Main St", "zip": 90210},
"private_field": "secret"
}
example_list: JSONType = [1, "hello", True, None, example_dict]
processed_data = process_json_data(example_list)
print(f"Original: {example_list}")
print(f"Processed: {processed_data}")