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:

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


Functions

dumps

def dumps(
    __obj: Any,
    default: Callable[[Any], Any] | None = ...,
    option: int | None = ...,
) -> bytes: ...
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: ...
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): ...
from orjson import loads, JSONDecodeError

try:
    loads(b'invalid json')
except JSONDecodeError as e:
    print("Failed to parse JSON:", e)

JSONEncodeError

class JSONEncodeError(TypeError): ...
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

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


Interaction with the System


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:**


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:

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.


End of Documentation for __init__.pyi