Coverage for src / lexigram / contracts / core / serialization.py: 0%

16 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-08-15 18:57 +0800

1"""Serialization protocol definitions for Lexigram contracts. 

2 

3Provides generic serialization protocols used across all extensions 

4(cache, messaging, tasks, etc.), plus the low-level JSON bytes protocol. 

5 

6The concrete implementations live in the respective extension packages. 

7""" 

8 

9from __future__ import annotations 

10 

11from typing import Any, Protocol, TypeVar, runtime_checkable 

12 

13T = TypeVar("T") 

14 

15 

16@runtime_checkable 

17class JsonSerializerProtocol(Protocol): 

18 """Protocol for JSON serializers.""" 

19 

20 def dumps(self, obj: Any) -> bytes: 

21 """Serialize object to JSON bytes.""" 

22 ... 

23 

24 def loads(self, data: bytes | str) -> Any: 

25 """Deserialize JSON bytes or string to object.""" 

26 ... 

27 

28 

29@runtime_checkable 

30class AsyncStringSerializerProtocol(Protocol): 

31 """Protocol for value serialization. 

32 

33 Implementations handle conversion between Python objects and string 

34 representations suitable for storage or transmission. Used across 

35 extensions (cache, messaging, tasks, etc.) for consistent serialization. 

36 

37 Example:: 

38 

39 class JSONSerializer: 

40 async def serialize(self, value: Any) -> str: 

41 return json.dumps(value) 

42 

43 async def deserialize(self, data: str) -> Any: 

44 return json.loads(data) 

45 """ 

46 

47 async def serialize(self, value: Any) -> str: 

48 """Serialize a Python object to string. 

49 

50 Args: 

51 value: Python object to serialize. 

52 

53 Returns: 

54 String representation. 

55 """ 

56 ... 

57 

58 async def deserialize(self, data: str) -> Any: 

59 """Deserialize string back to Python object. 

60 

61 Args: 

62 data: Serialized string data. 

63 

64 Returns: 

65 Reconstructed Python object. 

66 """ 

67 ... 

68 

69 

70@runtime_checkable 

71class SerializerProtocol(Protocol): 

72 """General-purpose serializer/deserializer with typed round-trip support.""" 

73 

74 def serialize(self, obj: Any) -> bytes: 

75 """Serialize *obj* to raw bytes.""" 

76 ... 

77 

78 def deserialize(self, data: bytes, type_: type[T]) -> T: 

79 """Deserialize *data* into an instance of *type_*.""" 

80 ... 

81 

82 

83__all__ = [ 

84 "AsyncStringSerializerProtocol", 

85 "JsonSerializerProtocol", 

86 "SerializerProtocol", 

87]