Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions msgpack/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# ruff: noqa: F401
# pyright: reportUnusedImport = none
import os
import typing as t

from .exceptions import * # noqa: F403
from .ext import ExtType, Timestamp
Expand All @@ -8,7 +10,7 @@
__version__ = "1.1.2"


if os.environ.get("MSGPACK_PUREPYTHON"):
if os.environ.get("MSGPACK_PUREPYTHON") or t.TYPE_CHECKING:
from .fallback import Packer, Unpacker, unpackb
else:
try:
Expand All @@ -17,26 +19,26 @@
from .fallback import Packer, Unpacker, unpackb


def pack(o, stream, **kwargs):
def pack(o: t.Any, stream: t.BinaryIO, **kwargs: dict[str, t.Any]):
"""
Pack object `o` and write it to `stream`

See :class:`Packer` for options.
"""
packer = Packer(**kwargs)
stream.write(packer.pack(o))
packer = Packer(autoreset=True, **kwargs) # type: ignore
stream.write(t.cast(bytes, packer.pack(o)))


def packb(o, **kwargs):
def packb(o: t.Any, **kwargs: dict[str, t.Any]):
"""
Pack object `o` and return packed bytes

See :class:`Packer` for options.
"""
return Packer(**kwargs).pack(o)
return Packer(autoreset=True, **kwargs).pack(o) # type: ignore


def unpack(stream, **kwargs):
def unpack(stream: t.BinaryIO, **kwargs: dict[str, t.Any]):
"""
Unpack an object from `stream`.

Expand Down
22 changes: 13 additions & 9 deletions msgpack/ext.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import datetime
import struct
import typing as t
from collections import namedtuple


class ExtType(namedtuple("ExtType", "code data")):
"""ExtType represents ext type in msgpack."""

def __new__(cls, code, data):
code: int
data: bytes

def __new__(cls, code: int, data: bytes):
if not isinstance(code, int):
raise TypeError("code must be int")
if not isinstance(data, bytes):
raise TypeError("data must be bytes")
if not 0 <= code <= 127:
raise ValueError("code must be 0~127")
return super().__new__(cls, code, data)
return super().__new__(cls, code, data) # type: ignore


class Timestamp:
Expand All @@ -28,7 +32,7 @@ class Timestamp:

__slots__ = ["seconds", "nanoseconds"]

def __init__(self, seconds, nanoseconds=0):
def __init__(self, seconds: int, nanoseconds=0):
"""Initialize a Timestamp object.

:param int seconds:
Expand All @@ -54,21 +58,21 @@ def __repr__(self):
"""String representation of Timestamp."""
return f"Timestamp(seconds={self.seconds}, nanoseconds={self.nanoseconds})"

def __eq__(self, other):
def __eq__(self, other: t.Any):
"""Check for equality with another Timestamp object"""
if type(other) is self.__class__:
return self.seconds == other.seconds and self.nanoseconds == other.nanoseconds
return False

def __ne__(self, other):
def __ne__(self, other: t.Any):
"""not-equals method (see :func:`__eq__()`)"""
return not self.__eq__(other)

def __hash__(self):
return hash((self.seconds, self.nanoseconds))

@staticmethod
def from_bytes(b):
def from_bytes(b: bytes):
"""Unpack bytes into a `Timestamp` object.

Used for pure-Python msgpack unpacking.
Expand Down Expand Up @@ -116,7 +120,7 @@ def to_bytes(self):
return data

@staticmethod
def from_unix(unix_sec):
def from_unix(unix_sec: int | float):
"""Create a Timestamp from posix timestamp in seconds.

:param unix_float: Posix timestamp in seconds.
Expand All @@ -135,7 +139,7 @@ def to_unix(self):
return self.seconds + self.nanoseconds / 1e9

@staticmethod
def from_unix_nano(unix_ns):
def from_unix_nano(unix_ns: int):
"""Create a Timestamp from posix timestamp in nanoseconds.

:param int unix_ns: Posix timestamp in nanoseconds.
Expand All @@ -162,7 +166,7 @@ def to_datetime(self):
)

@staticmethod
def from_datetime(dt):
def from_datetime(dt: datetime.datetime):
"""Create a Timestamp from datetime with tzinfo.

:rtype: Timestamp
Expand Down
Loading