Typing Stubs for orjson
types-orjson provides type hints (typing stubs) for the high-performance `orjson` JSON library. It is part of the Python `typeshed` project, which maintains type stubs for various third-party packages. These stubs enable static type checkers like MyPy or Pyright to validate `orjson`'s API usage, enhancing code reliability and developer experience. The current version is 3.6.2, and updates are typically released in sync with `typeshed`'s update cycle or when `orjson` has significant API changes.
Warnings
- gotcha Installing `types-orjson` alone is not enough. You must also install the actual `orjson` library for your code to run at runtime. `types-orjson` only provides type hints for `orjson`.
- gotcha `types-orjson` provides static type information for type checkers (e.g., MyPy, Pyright) only. It does not add any runtime functionality or change the behavior of `orjson` itself. Your code will function identically at runtime with or without `types-orjson` installed.
- breaking While `typeshed` strives to keep stubs up-to-date, significant API changes in `orjson` itself might lead to temporary inconsistencies or outdated type hints in `types-orjson` until the stubs are updated. This typically means your type checker might report errors even if the runtime code is correct for a new `orjson` version.
Install
-
pip install types-orjson orjson
Imports
- orjson
from types_orjson import ...
import orjson
Quickstart
import orjson
from typing import Any, Dict
def process_data(data_str: str) -> Dict[str, Any]:
# orjson.loads provides type hints thanks to types-orjson
parsed_data: Dict[str, Any] = orjson.loads(data_str)
# orjson.dumps provides type hints
re_serialized_data: bytes = orjson.dumps(parsed_data, option=orjson.OPT_INDENT_2)
print(re_serialized_data.decode())
return parsed_data
if __name__ == '__main__':
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
result = process_data(json_string)
print(f"Parsed data: {result}")
# To verify types, run a type checker:
# mypy your_script_name.py
# or pyright your_script_name.py