init.py


Overview

The `__init__.py` file serves as the primary Python API entry point for the `orjson` package, which provides ultra-fast JSON serialization and deserialization by leveraging a Rust implementation under the hood. This file's main purpose is to **import and re-export the Rust extension module's functions, classes, and constants into the Python package namespace**, presenting a clean and Pythonic API surface.

By doing so, it abstracts away the complexities of the underlying Rust FFI (Foreign Function Interface) bindings and exposes a stable, user-friendly interface for Python developers. This includes serialization and deserialization functions, error classes, JSON fragment representations, and a comprehensive set of serialization option flags.


Detailed Explanation

Imports

from .orjson import *
from .orjson import __version__

This design pattern centralizes the API exports, allowing users to interact with `orjson` functions and constants simply by importing from the package root.


__all__ Declaration

__all__ = (
    "__version__",
    "dumps",
    "Fragment",
    "JSONDecodeError",
    "JSONEncodeError",
    "loads",
    "OPT_APPEND_NEWLINE",
    "OPT_INDENT_2",
    "OPT_NAIVE_UTC",
    "OPT_NON_STR_KEYS",
    "OPT_OMIT_MICROSECONDS",
    "OPT_PASSTHROUGH_DATACLASS",
    "OPT_PASSTHROUGH_DATETIME",
    "OPT_PASSTHROUGH_SUBCLASS",
    "OPT_SERIALIZE_DATACLASS",
    "OPT_SERIALIZE_NUMPY",
    "OPT_SERIALIZE_UUID",
    "OPT_SORT_KEYS",
    "OPT_STRICT_INTEGER",
    "OPT_UTC_Z",
)

Key API Components Exposed by __init__.py

Symbol

Type

Description

`__version__`

`str`

Version string of the `orjson` package.

`dumps(obj, default=None, option=None) -> bytes`

Function

Serializes a Python object into JSON-formatted bytes using Rust's high-performance serializer.

`loads(obj) -> Any`

Function

Parses JSON bytes or string into Python objects using Rust's parser.

`Fragment`

Class

Represents a partial JSON fragment; useful for advanced serialization scenarios.

`JSONDecodeError`

Exception Class

Raised on JSON decoding errors; subclasses Python's `json.JSONDecodeError`.

`JSONEncodeError`

Exception Class

Raised on JSON encoding errors; subclasses `TypeError`.

`OPT_*` constants

`int` bitflags

Serialization options controlling output formatting, key handling, datetime processing, etc.


Usage Examples

Basic Serialization

import orjson

data = {"name": "Alice", "age": 30}
json_bytes = orjson.dumps(data)
print(json_bytes)  # b'{"name":"Alice","age":30}'

Deserialization

json_str = b'{"name":"Alice","age":30}'
obj = orjson.loads(json_str)
print(obj)  # {'name': 'Alice', 'age': 30}

Using Serialization Options

json_bytes = orjson.dumps(
    data,
    option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS
)
print(json_bytes.decode())
# {
#   "age": 30,
#   "name": "Alice"
# }

Handling Errors

try:
    orjson.loads(b'invalid json')
except orjson.JSONDecodeError as e:
    print(f"Decode error: {e}")

Important Implementation Details


Interaction with Other Parts of the System

This layered architecture cleanly separates concerns, enabling maintainability, performance, and usability.


Visual Diagram: Class and Symbol Structure of __init__.py

classDiagram
    class orjson {
        <<module>>
        +__version__: str
        +dumps(obj: Any, default: Callable | None, option: int | None) bytes
        +loads(obj: bytes | str) Any
        +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: int
    }

    class Fragment {
        +contents: bytes | str
    }

    class JSONDecodeError {
        <<exception>>
    }

    class JSONEncodeError {
        <<exception>>
    }

    orjson <|-- Fragment
    orjson <|-- JSONDecodeError
    orjson <|-- JSONEncodeError

Summary

The `__init__.py` file in the `orjson` package acts as the **Python API gateway to the Rust-implemented JSON processing functionality**. It imports and re-exports:

This setup provides Python developers with a fast, reliable, and easy-to-use JSON library that leverages Rust’s performance while maintaining Pythonic usability and error semantics.


End of Documentation for __init__.py