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

Add dataclass coder #119

Merged
merged 5 commits into from
Apr 20, 2019
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
1 change: 1 addition & 0 deletions docs/coder.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ modern Python world.
ring.coder.bypass_coder
ring.coder.JsonCoder
ring.coder.pickle_coder
ring.coder.DataclassCoder

:see: :mod:`ring.coder` for the module including pre-registered coders.

Expand Down
29 changes: 27 additions & 2 deletions ring/coder.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import abc
import six
from collections import namedtuple

try:
import ujson as json_mod
except ImportError:
Expand All @@ -17,6 +18,11 @@
except ImportError:
import pickle as pickle_mod

try:
import dataclasses
except ImportError:
dataclasses = None


@six.add_metaclass(abc.ABCMeta)
class Coder(object):
Expand Down Expand Up @@ -63,7 +69,7 @@ class Registry(object):
:see: :func:`ring.coder.registry` for default registry instance.
"""

__slots__ = ('coders', )
__slots__ = ('coders',)

def __init__(self):
self.coders = {}
Expand Down Expand Up @@ -113,7 +119,6 @@ def bypass(x):
#: encode and decode functions bypass the given parameter.
bypass_coder = bypass, bypass


#: Pickle coder.
#:
#: encode is :func:`pickle.dumps` and decode is :func:`pickle.loads`.
Expand All @@ -139,6 +144,23 @@ def decode(binary):
return json_mod.loads(binary.decode('utf-8'))


if dataclasses:
class DataclassCoder(Coder):

@staticmethod
def encode(data):
"""Serialize dataclass object to json encoded dictionary"""
target_dict = (type(data).__name__, dataclasses.asdict(data))
return JsonCoder.encode(target_dict)

@staticmethod
def decode(binary):
"""Deserialize json encoded dictionary to dataclass object"""
name, fields = JsonCoder.decode(binary)
dataclass = dataclasses.make_dataclass(name, [(key, type(value)) for key, value in fields.items()])
instance = dataclass(**fields)
return instance

#: The default coder registry with pre-registered coders.
#: Built-in coders are registered by default.
#:
Expand All @@ -147,3 +169,6 @@ def decode(binary):
registry.register(None, bypass_coder)
registry.register('json', JsonCoder())
registry.register('pickle', pickle_coder)

if dataclasses:
registry.register('dataclass', DataclassCoder())
16 changes: 16 additions & 0 deletions tests/test_coder.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys

import ring
from ring.coder import (
Expand Down Expand Up @@ -82,6 +83,21 @@ def f():
assert f() == 10


if sys.version_info >= (3, 7):
from tests._test_module_py37 import DataClass

def test_dataclass_coder():
coder = default_registry.get('dataclass')
dataclass = DataClass('name', 1, {'test': 1})
encoded_dataclass = coder.encode(dataclass)
assert b'["DataClass", {"name": "name", "my_int": 1, "my_dict": {"test": 1}}]' == encoded_dataclass
decoded_dataclass = coder.decode(encoded_dataclass)
assert 'DataClass' == type(decoded_dataclass).__name__
assert decoded_dataclass.name == 'name'
assert decoded_dataclass.my_int == 1
assert decoded_dataclass.my_dict == {'test': 1}


def test_unexisting_coder():
cache = {}

Expand Down