Python API Package
Purpose
This subtopic defines the Python-facing package interface that exposes the Rust-accelerated JSON serialization and deserialization functionality. It addresses the need for a clean, stable, and idiomatic Python API that serves as the entry point for all orjson users. By consolidating exports, type declarations, and error classes, it provides a consistent environment that abstracts the underlying Rust FFI complexity and enables seamless usage in Python applications.
Functionality
The Python API package primarily:
Imports and re-exports core serialization/deserialization functions (
dumps,loads) implemented in Rust.Defines and exposes custom error classes (
JSONDecodeError,JSONEncodeError) that wrap lower-level exceptions, enabling Pythonic error handling.Declares a
Fragmentclass to represent partial JSON fragments with typed contents.Provides a comprehensive set of serialization option constants (e.g.,
OPT_INDENT_2,OPT_SORT_KEYS) as integer flags to control serialization behavior.Includes type hinting information (
.pyistub) to improve developer experience with autocompletion and static analysis tools.Uses
__all__to explicitly define the API surface, ensuring only intended components are imported viafrom orjson import *.
These elements collectively allow Python developers to interact with orjson as a natural extension of the Python standard library's `json` module but with significant performance and feature enhancements.
Key Methods and Constants
dumps(obj, default=None, option=None) -> bytes
Serializes Python objects to JSON bytes with optional fallback serialization (default) and bitwise serialization options.loads(obj) -> Any
Deserializes JSON input from bytes, bytearray, memoryview, or string into corresponding Python objects.Serialization option flags (examples):
OPT_INDENT_2: Pretty-print output with two-space indentation.OPT_SORT_KEYS: Sort dictionary keys for deterministic output.OPT_SERIALIZE_NUMPY: Support serialization of numpy arrays.
Error Classes
JSONDecodeError: Raised on invalid JSON input during deserialization.JSONEncodeError: Raised on unsupported or invalid data types during serialization.
Fragment Class
A lightweight wrapper representing a JSON fragment, typically used internally or for advanced use cases where partial serialization output is needed.
Integration
This package acts as the bridge between Python code and the Rust FFI layer described in the parent topic. It imports the Rust-backed `orjson` module and exposes its functionality in a Python-native manner.
It complements the overall FFI bindings by focusing on Python usability rather than low-level interop.
The option flags it exposes are used internally by Rust serialization routines, enabling flexible behavior without Python users needing to manage bitmasks manually.
Error classes correspond to Rust error types, maintaining error semantics across the language boundary.
The package is foundational for all user-facing workflows, including serialization, deserialization, and error handling, thus tightly coupling it with other subtopics that implement core logic or extend functionality (e.g., custom serialization support).
Diagram
classDiagram
class PythonAPIPackage {
+bytes dumps(obj: Any, default: Callable | None, option: int | None)
+Any loads(obj: bytes | str)
+int OPT_INDENT_2
+int OPT_SORT_KEYS
+int OPT_SERIALIZE_NUMPY
+...
}
class JSONDecodeError {
<<exception>>
}
class JSONEncodeError {
<<exception>>
}
class Fragment {
+bytes|str contents
}
PythonAPIPackage "1" o-- "1" JSONDecodeError : raises
PythonAPIPackage "1" o-- "1" JSONEncodeError : raises
PythonAPIPackage "1" o-- "1" Fragment : defines
note for PythonAPIPackage "Imports Rust-backed orjson module\nRe-exports core functions and constants"
Code Snippet Illustrating Key Export
# pysrc/orjson/__init__.py (excerpt)
from .orjson import *
from .orjson import __version__
__all__ = (
"__version__",
"dumps",
"loads",
"JSONDecodeError",
"JSONEncodeError",
"Fragment",
"OPT_INDENT_2",
"OPT_SORT_KEYS",
"OPT_SERIALIZE_NUMPY",
# ... additional options
)
This snippet shows how the package re-exports Rust module symbols and explicitly specifies the public API surface, enabling clean imports and consistent usage patterns.
By serving as the Python interface layer, the Python API package ensures that orjson’s powerful Rust-based JSON processing capabilities are accessible, intuitive, and maintainable for Python developers.