msgpack-python/msgpack/__init__.py

58 lines
1.3 KiB
Python
Raw Normal View History

# ruff: noqa: F401
2026-01-02 22:44:06 +08:00
# pyright: reportUnusedImport = none
import os
2026-01-02 22:44:06 +08:00
import typing as t
2013-10-21 00:59:22 +09:00
from .exceptions import * # noqa: F403
from .ext import ExtType, Timestamp
2025-10-08 17:56:20 +09:00
version = (1, 1, 2)
__version__ = "1.1.2"
2026-01-02 22:44:06 +08:00
if os.environ.get("MSGPACK_PUREPYTHON") or t.TYPE_CHECKING:
from .fallback import Packer, Unpacker, unpackb
else:
try:
from ._cmsgpack import Packer, Unpacker, unpackb
except ImportError:
from .fallback import Packer, Unpacker, unpackb
2013-10-17 08:44:25 +09:00
2026-01-02 22:44:06 +08:00
def pack(o: t.Any, stream: t.BinaryIO, **kwargs: dict[str, t.Any]):
2013-10-17 08:44:25 +09:00
"""
Pack object `o` and write it to `stream`
See :class:`Packer` for options.
"""
2026-01-02 22:44:06 +08:00
packer = Packer(autoreset=True, **kwargs) # type: ignore
stream.write(t.cast(bytes, packer.pack(o)))
2013-10-17 08:44:25 +09:00
2013-10-20 20:28:32 +09:00
2026-01-02 22:44:06 +08:00
def packb(o: t.Any, **kwargs: dict[str, t.Any]):
2013-10-17 08:44:25 +09:00
"""
Pack object `o` and return packed bytes
See :class:`Packer` for options.
"""
2026-01-02 22:44:06 +08:00
return Packer(autoreset=True, **kwargs).pack(o) # type: ignore
2013-10-17 08:44:25 +09:00
2026-01-02 22:44:06 +08:00
def unpack(stream: t.BinaryIO, **kwargs: dict[str, t.Any]):
"""
Unpack an object from `stream`.
Raises `ExtraData` when `stream` contains extra bytes.
See :class:`Unpacker` for options.
"""
data = stream.read()
return unpackb(data, **kwargs)
# alias for compatibility to simplejson/marshal/pickle.
load = unpack
loads = unpackb
dump = pack
dumps = packb