Skip to content
Merged
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
4 changes: 2 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
fail-fast: false
matrix:
os: ["ubuntu-latest", "windows-latest"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
python-version: ["3.10", "3.11", "3.12", "3.13"]
runs-on: ${{ matrix.os }}

steps:
Expand Down Expand Up @@ -174,4 +174,4 @@ jobs:
# uses: codecov/codecov-action@v5.5.1
# with:
# token: ${{ secrets.CODECOV_TOKEN }}
# files: coverage.xml
# files: coverage.xml
131 changes: 128 additions & 3 deletions src/serializall/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
@author: Sebastien Weber
"""
import numbers
from typing import Tuple, List
from typing import Tuple, List, Union
from collections import OrderedDict
from datetime import date, datetime, time
from pathlib import Path, PosixPath, PurePath, WindowsPath

import numpy as np

Expand Down Expand Up @@ -387,6 +389,105 @@ def deserialize(bytes_str: bytes) -> Tuple[OrderedDict, bytes]:
return OrderedDict(dict_list), remaining_bytes


class NumpyScalarSerializeDeserialize(SerializableBase):
"""Numpy scalars (np.float32, np.int8, np.bool_...): same bytes as the python scalars, but the
deserialized object is a numpy scalar of the same dtype.

The python-compatible types np.float64, np.int64, np.complex128 and np.bool_ are deserialized as the
python float, int, complex and bool: same value, same behaviour, and what libraries expect (json...).
"""
@staticmethod
def serialize(scalar: np.generic) -> bytes:
""" Convert a numpy scalar into a bytes message: dtype, length, raw bytes """
array = np.array([scalar])
data_bytes = array.tobytes()
bytes_string = StringSerializeDeserialize.serialize(array.dtype.descr[0][1])
bytes_string += utils.int_to_bytes(len(data_bytes))
bytes_string += data_bytes
return bytes_string

@staticmethod
def deserialize(bytes_str: bytes) -> Tuple[np.generic, bytes]:
""" Convert bytes into a numpy scalar of the serialized dtype

Returns
-------
np.generic: the decoded scalar
bytes: the remaining bytes string if any
"""
data_type, remaining_bytes = StringSerializeDeserialize.deserialize(bytes_str)
data_len, remaining_bytes = utils.get_int_from_bytes(remaining_bytes)
number_bytes, remaining_bytes = utils.split_nbytes(remaining_bytes, data_len)
return np.frombuffer(number_bytes, dtype=data_type)[0], remaining_bytes


class SetSerializeDeserialize(SerializableBase):
"""set and frozenset, serialized as a list of their items (in no particular order)"""
@staticmethod
def serialize(set_object: Union[set, frozenset]) -> bytes:
return ListSerializeDeserialize.serialize(list(set_object))

@staticmethod
def deserialize(bytes_str: bytes) -> Tuple[set, bytes]:
items, remaining_bytes = ListSerializeDeserialize.deserialize(bytes_str)
return set(items), remaining_bytes


class FrozenSetSerializeDeserialize(SetSerializeDeserialize):
@staticmethod
def deserialize(bytes_str: bytes) -> Tuple[frozenset, bytes]:
items, remaining_bytes = ListSerializeDeserialize.deserialize(bytes_str)
return frozenset(items), remaining_bytes


class PathSerializeDeserialize(SerializableBase):
"""pathlib paths, serialized as a string and rebuilt as a ``pathlib.Path`` of the local platform"""
@staticmethod
def serialize(path: PurePath) -> bytes:
return StringSerializeDeserialize.serialize(str(path))

@staticmethod
def deserialize(bytes_str: bytes) -> Tuple[Path, bytes]:
path_str, remaining_bytes = StringSerializeDeserialize.deserialize(bytes_str)
return Path(path_str), remaining_bytes


class DatetimeSerializeDeserialize(SerializableBase):
"""datetime, serialized as an ISO 8601 string (timezone and microseconds are kept)"""
@staticmethod
def serialize(dt: datetime) -> bytes:
return StringSerializeDeserialize.serialize(dt.isoformat())

@staticmethod
def deserialize(bytes_str: bytes) -> Tuple[datetime, bytes]:
iso, remaining_bytes = StringSerializeDeserialize.deserialize(bytes_str)
return datetime.fromisoformat(iso), remaining_bytes


class DateSerializeDeserialize(SerializableBase):
"""date, serialized as an ISO 8601 string"""
@staticmethod
def serialize(d: date) -> bytes:
return StringSerializeDeserialize.serialize(d.isoformat())

@staticmethod
def deserialize(bytes_str: bytes) -> Tuple[date, bytes]:
iso, remaining_bytes = StringSerializeDeserialize.deserialize(bytes_str)
return date.fromisoformat(iso), remaining_bytes


class TimeSerializeDeserialize(SerializableBase):
"""time, serialized as an ISO 8601 string"""
@staticmethod
def serialize(t: time) -> bytes:
return StringSerializeDeserialize.serialize(t.isoformat())

@staticmethod
def deserialize(bytes_str: bytes) -> Tuple[time, bytes]:
iso, remaining_bytes = StringSerializeDeserialize.deserialize(bytes_str)
return time.fromisoformat(iso), remaining_bytes


ser_factory.register_from_type(
type(None), NoneSerializeDeserialize.serialize, NoneSerializeDeserialize.deserialize
)
Expand Down Expand Up @@ -422,5 +523,29 @@ def deserialize(bytes_str: bytes) -> Tuple[OrderedDict, bytes]:
OrderedDictSerializeDeserialize.serialize,
OrderedDictSerializeDeserialize.deserialize)



# numpy scalars: the type name written in the stream is the numpy class name (float32, int8...)
for _np_type in (np.float16, np.float32, np.int8, np.int16, np.int32, np.uint8, np.uint16, np.uint32,
np.uint64, np.complex64):
ser_factory.register_from_type(_np_type,
NumpyScalarSerializeDeserialize.serialize,
NumpyScalarSerializeDeserialize.deserialize)
# the numpy scalars having an exact python equivalent are deserialized as the python type
for _np_type in (np.float64, np.int64, np.complex128):
ser_factory.register_from_type(_np_type,
NumpyScalarSerializeDeserialize.serialize,
ScalarSerializeDeserialize.deserialize)
# np.bool_ is named 'bool' in the stream and is therefore deserialized as the python bool
ser_factory.register_from_type(np.bool_,
NumpyScalarSerializeDeserialize.serialize,
ScalarSerializeDeserialize.deserialize)

ser_factory.register_from_type(set, SetSerializeDeserialize.serialize, SetSerializeDeserialize.deserialize)
ser_factory.register_from_type(frozenset, FrozenSetSerializeDeserialize.serialize,
FrozenSetSerializeDeserialize.deserialize)
for _path_type in (PosixPath, WindowsPath):
ser_factory.register_from_type(_path_type, PathSerializeDeserialize.serialize,
PathSerializeDeserialize.deserialize)
ser_factory.register_from_type(datetime, DatetimeSerializeDeserialize.serialize,
DatetimeSerializeDeserialize.deserialize)
ser_factory.register_from_type(date, DateSerializeDeserialize.serialize, DateSerializeDeserialize.deserialize)
ser_factory.register_from_type(time, TimeSerializeDeserialize.serialize, TimeSerializeDeserialize.deserialize)
46 changes: 46 additions & 0 deletions tests/serializer_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import numpy as np
import pytest
from collections import OrderedDict
from datetime import date, datetime, time, timezone
from pathlib import Path, PurePath

from serializall.factory import SerializableFactory
from serializall.serializer import (StringSerializeDeserialize as SSD,
Expand Down Expand Up @@ -270,3 +272,47 @@ def test_registration_without_serialization():
class TestClass:
def __init__(self):
self.a = 'a'


NUMPY_KEPT = [np.float16(1.5), np.float32(0.1), np.int8(-3), np.int16(7), np.int32(3), np.uint8(200),
np.uint16(7), np.uint32(9), np.uint64(2 ** 63 + 1), np.complex64(1 + 2j)]


@pytest.mark.parametrize('scalar', NUMPY_KEPT)
def test_numpy_scalar_keeps_its_dtype(scalar):
result = ser_factory.get_apply_deserializer(ser_factory.get_apply_serializer(scalar))
assert type(result) is type(scalar)
assert result == scalar


@pytest.mark.parametrize('scalar, python_type', [(np.float64(1.5), float), (np.int64(-3), int),
(np.complex128(1 + 2j), complex), (np.bool_(True), bool)])
def test_numpy_scalar_with_python_equivalent_becomes_python(scalar, python_type):
result = ser_factory.get_apply_deserializer(ser_factory.get_apply_serializer(scalar))
assert type(result) is python_type
assert result == scalar


@pytest.mark.parametrize('obj', [{1, 'a', 2.5}, set(), frozenset({1, 2}),
Path('/some/path/file.h5'), Path('relative') / 'file',
datetime(2026, 11, 14, 13, 47, 6, 123456),
datetime(2026, 1, 1, tzinfo=timezone.utc),
date(2026, 11, 14), time(13, 47, 6, 5)])
def test_standard_types_round_trip(obj):
result = ser_factory.get_apply_deserializer(ser_factory.get_apply_serializer(obj))
assert result == obj
assert isinstance(result, type(obj)) or isinstance(obj, PurePath)


def test_new_types_inside_containers_with_remaining_bytes():
obj = {'a': [np.float32(1), {1, 2}], 'b': (Path('/x'), datetime(2026, 1, 1)), 'c': np.int32(4)}
bytes_str = ser_factory.get_apply_serializer(obj) + b'rest'
result, remaining = ser_factory.get_apply_deserializer(bytes_str, only_object=False)
assert remaining == b'rest'
assert result == obj
assert type(result['c']) is np.int32 and type(result['a'][0]) is np.float32


def test_unregistered_type_still_raises():
with pytest.raises(NotImplementedError):
ser_factory.get_apply_serializer(object())
Loading