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__
Imports all public symbols from the Rust-backed
orjsonextension module located in the same package directory.Explicitly imports
__version__to expose the package version string.
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",
)
Defines the explicit list of public API symbols exported when a user performs:
from orjson import *Controls namespace pollution by restricting exports to intended functions, classes, and constants.
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
This file does not implement any logic internally; it serves as a facade by re-exporting the Rust extension module's symbols.
The Rust extension module (
orjson) is compiled from Rust source code using PyO3, which provides:Efficient JSON serialization/deserialization.
Python exception translation.
Definition of option flags as integer bitmasks.
The
__all__tuple ensures that only intended API components are publicly accessible, promoting clean namespace management.By importing everything (
*) from the Rust module, the package maintains parity with the Rust implementation without duplicating code.
Interaction with Other Parts of the System
Rust Extension Module (
orjson): The core JSON serialization and deserialization logic lives here, implemented in Rust and exposed as a Python extension.FFI Layer: Bridges Rust and Python, automatically converting data types and errors.
Python Package Layer (
__init__.py): This file provides the Pythonic interface, importing from the Rust extension and exposing symbols for Python users.Testing and Benchmarking: Use this API surface to validate correctness and measure performance.
Type Hinting Stub (
__init__.pyi): Provides function signatures and class definitions for IDEs and static type checkers.
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:
Core serialization (
dumps) and deserialization (loads) functions.JSON fragment class.
Custom error classes for idiomatic Python exception handling.
A rich set of serialization option flags controlling formatting, key handling, and special data type support.
The version string.
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.