Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat[serializers]: specify default JSON encoders to make subclassing more easily #42

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,22 @@ NULL_BYTE: Final = b"\x00"


class JSONSerializer:

encoder = json.JSONEncoder
decoder = json.JSONDecoder

def dumps(self, obj: dict) -> bytes:
try:
return json.dumps(obj).encode() + NULL_BYTE
return json.dumps(obj, cls=self.encoder).encode() + NULL_BYTE
except (ValueError, TypeError):
raise SerializationError(obj)

def loads(self, data: bytes) -> dict:
data = data.split(NULL_BYTE, 1)[0]
try:
return json.loads(data)
return json.loads(data, cls=self.decoder)
except json.JSONDecodeError:
raise DeserializationError(data)

```

Note: A null byte is used to separate the dictionary contents from the bytes that are in memory.
Expand Down
13 changes: 11 additions & 2 deletions shared_memory_dict/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,30 @@ def loads(self, data: bytes) -> dict:


class JSONSerializer:

__slots__ = ()

encoder = json.JSONEncoder
decoder = json.JSONDecoder

def dumps(self, obj: dict) -> bytes:
try:
return json.dumps(obj).encode() + NULL_BYTE
return json.dumps(obj, cls=self.encoder).encode() + NULL_BYTE
except (ValueError, TypeError):
raise SerializationError(obj)

def loads(self, data: bytes) -> dict:
data = data.split(NULL_BYTE, 1)[0]
try:
return json.loads(data)
return json.loads(data, cls=self.decoder)
except json.JSONDecodeError:
raise DeserializationError(data)


class PickleSerializer:

__slots__ = ()

def dumps(self, obj: dict) -> bytes:
try:
return pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
Expand Down