init.pyi
Overview
The `__init__.pyi` file serves as the **type hinting stub** for the Python package interface of the `orjson` module, a high-performance JSON library implemented with a Rust core. This stub file provides explicit type annotations, function signatures, class declarations, constants, and exception definitions that describe the public API exposed by the compiled Rust extension module.
Its primary purpose is to enable:
Static type checking by tools like
mypy.IDE autocompletion and inline documentation to improve developer experience.
Clear contract specification of functions, classes, and constants without exposing implementation details.
Seamless integration with Python typing standards, especially for complex types involving callables and union types.
The file outlines key components such as the serialization and deserialization functions, custom exceptions, a lightweight `Fragment` class, and numerous integer constants representing serialization options.
Detailed API Documentation
Module-Level Variables
version: str
A string representing the current version of theorjsonlibrary. This allows users to programmatically check the installed package version.
Functions
dumps
def dumps(
__obj: Any,
default: Callable[[Any], Any] | None = ...,
option: int | None = ...,
) -> bytes: ...
Purpose:
Serializes a Python object (__obj) into JSON-formatted bytes using Rust's efficient JSON serializer.Parameters:
__obj: Any
The Python object to serialize to JSON. This can be any serializable Python data structure or object.default: Callable[[Any], Any] | None = ...(optional)
An optional callable function that will be called for objects that are not serializable by default. It should accept the unserializable object and return a serializable replacement. IfNone, no fallback serialization is performed.option: int | None = ...(optional)
An optional bitmask of integer flags that customize serialization behavior (e.g., pretty printing, key sorting, datetime handling). IfNone, default serialization options are applied.
Returns:
bytes: The JSON output as UTF-8 encoded bytes.
Usage Example:
from orjson import dumps, OPT_INDENT_2
data = {"name": "Alice", "age": 30}
# Serialize with pretty-print option
json_bytes = dumps(data, option=OPT_INDENT_2)
print(json_bytes.decode("utf-8"))
loads
def loads(__obj: bytes | bytearray | memoryview | str) -> Any: ...
Purpose:
Parses JSON input and deserializes it into Python objects.Parameters:
__obj: bytes | bytearray | memoryview | str
JSON input as bytes, bytearray, memoryview, or Unicode string.
Returns:
Any: The corresponding Python object representation of the JSON input.
Usage Example:
from orjson import loads
json_bytes = b'{"key": "value", "num": 42}'
data = loads(json_bytes)
print(data) # Output: {'key': 'value', 'num': 42}
Classes
JSONDecodeError
class JSONDecodeError(json.JSONDecodeError): ...
Purpose:
Exception raised when JSON deserialization fails due to invalid or malformed input.Inheritance:
Subclasses Python’s built-injson.JSONDecodeErrorfor compatibility with standard JSON error handling.Behavior:
Raised byloads()when parsing errors occur, providing details about the error location and reason.Usage Example:
from orjson import loads, JSONDecodeError
try:
loads(b'invalid json')
except JSONDecodeError as e:
print("Failed to parse JSON:", e)
JSONEncodeError
class JSONEncodeError(TypeError): ...
Purpose:
Exception raised when JSON serialization fails, typically due to unsupported Python types or serialization issues.Inheritance:
Subclasses Python’s built-inTypeError.Behavior:
Raised bydumps()when unable to serialize a Python object.Usage Example:
from orjson import dumps, JSONEncodeError
class CustomClass:
pass
try:
dumps(CustomClass())
except JSONEncodeError as e:
print("Serialization error:", e)
Fragment
class Fragment(tuple):
contents: bytes | str
Purpose:
Represents a lightweight JSON fragment, typically used for partial serialization or advanced use cases.Inheritance:
Subclasses Python’s immutabletuple.Attributes:
contents: bytes | str
Holds the JSON fragment content either as bytes or string.
Usage Notes:
This class is mostly used internally or for specialized workflows where partial JSON output fragments are manipulated or combined.
Serialization Option Constants
The following integer constants represent bitmask flags to customize serialization behavior. These flags are passed as the `option` parameter to `dumps()`.
Constant | Description |
|---|---|
`OPT_APPEND_NEWLINE` | Append a newline character to the serialized JSON output. |
`OPT_INDENT_2` | Pretty-print JSON with 2 spaces indentation. |
`OPT_NAIVE_UTC` | Serialize datetime objects as naive UTC without timezone info. |
`OPT_NON_STR_KEYS` | Allow non-string dictionary keys by serializing them as strings. |
`OPT_OMIT_MICROSECONDS` | Omit microseconds in datetime serialization. |
`OPT_PASSTHROUGH_DATACLASS` | Pass through dataclasses without serialization. |
`OPT_PASSTHROUGH_DATETIME` | Pass through datetime objects without conversion. |
`OPT_PASSTHROUGH_SUBCLASS` | Pass through subclasses without serialization. |
`OPT_SERIALIZE_DATACLASS` | Serialize Python dataclasses automatically. |
`OPT_SERIALIZE_NUMPY` | Serialize NumPy arrays natively. |
`OPT_SERIALIZE_UUID` | Serialize UUID objects natively. |
`OPT_SORT_KEYS` | Sort dictionary keys in output for deterministic JSON. |
`OPT_STRICT_INTEGER` | Enforce strict integer serialization (e.g., no overflow). |
`OPT_UTC_Z` | Serialize UTC timezone as "Z" instead of "+00:00". |
**Note:** These constants are declared as integers and can be combined via bitwise OR to apply multiple options simultaneously.
Important Implementation Details
Type Hinting Stub Only:
The__init__.pyifile contains no executable code; it only declares types and signatures for static analysis tools and IDEs.Python-Rust FFI Boundary:
The actual implementations ofdumps,loads, exception classes, and option constants reside in the compiled Rust extension module, which this stub describes.Use of Union Types and Optional Defaults:
The function signatures use Python 3.10+ union type syntax (|) and ellipsis...to indicate optional parameters with default values.Exception Subclassing:
Custom exceptions subclass standard Python exceptions to maintain compatibility and expected behavior in Python error handling workflows.
Interaction with the System
Bridge to Rust Core:
This stub file represents the Python interface to theorjsonRust core module, which provides actual serialization/deserialization logic.Integration in Python Package:
The__init__.pyfile (and its stub) re-export Rust module functions and constants, making them accessible as if they were native Python code.Used by Static Analysis and IDEs:
Tools likemypy, PyCharm, VSCode, and others use this stub to provide type checking and code completion for users of theorjsonlibrary.Error Handling Workflow:
Exceptions declared here align with the errors raised from Rust, enabling Python users to handle serialization and deserialization errors idiomatically.
Visual Diagram
classDiagram
class orjson {
+bytes dumps(obj: Any, default: Callable | None, option: int | None)
+Any loads(obj: bytes | bytearray | memoryview | str)
+int OPT_APPEND_NEWLINE
+int OPT_INDENT_2
+int OPT_NAIVE_UTC
+int OPT_NON_STR_KEYS
+int OPT_OMIT_MICROSECONDS
+int OPT_PASSTHROUGH_DATACLASS
+int OPT_PASSTHROUGH_DATETIME
+int OPT_PASSTHROUGH_SUBCLASS
+int OPT_SERIALIZE_DATACLASS
+int OPT_SERIALIZE_NUMPY
+int OPT_SERIALIZE_UUID
+int OPT_SORT_KEYS
+int OPT_STRICT_INTEGER
+int OPT_UTC_Z
}
class JSONDecodeError {
<<exception>>
}
class JSONEncodeError {
<<exception>>
}
class Fragment {
+bytes|str contents
}
orjson "1" o-- "1" JSONDecodeError : raises
orjson "1" o-- "1" JSONEncodeError : raises
orjson "1" o-- "1" Fragment : defines
**Diagram Explanation:**
The
orjsonclass represents the module namespace exposing functions and serialization option constants.It defines two exception classes (
JSONDecodeError,JSONEncodeError) that it can raise during operation.The
Fragmentclass is also part of the public API, encapsulating partial JSON content.This class diagram clarifies the relationships between the module’s API elements.
Summary
The `__init__.pyi` file for `orjson` is a crucial type hinting interface that describes the Python API surface of the Rust-backed JSON library. It defines:
The key serialization (
dumps) and deserialization (loads) functions with precise type signatures.Custom exceptions for encoding and decoding errors that integrate seamlessly with Python’s standard library exceptions.
A
Fragmentclass used for partial JSON representation.Numerous integer constants representing serialization options to customize behavior.
This stub file enables static type checking, improves developer tooling support, and documents the expected API contract without exposing implementation details, thus enhancing usability and reliability of the Python `orjson` package.