Skip to content

Added support for dataclasses #26

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
23 changes: 17 additions & 6 deletions mapper/object_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
"""
Copyright (C) 2015, marazt. All rights reserved.
"""
from inspect import getmembers, isroutine
from inspect import getmembers, isroutine, isclass
from datetime import date, datetime
from dataclasses import is_dataclass, MISSING

from mapper.casedict import CaseDict
from mapper.object_mapper_exception import ObjectMapperException
Expand Down Expand Up @@ -101,11 +102,11 @@ def create_map(self, type_from, type_to, mapping=None):
:return: None
"""

if (type(type_from) is not type):
raise ObjectMapperException("type_from must be a type")
if not isclass(type_from):
raise ObjectMapperException("type_from must be a class")

if (type(type_to) is not type):
raise ObjectMapperException("type_to must be a type")
if not isclass(type_to):
raise ObjectMapperException("type_to must be a class")

if (mapping is not None and not isinstance(mapping, dict)):
raise ObjectMapperException("mapping, if provided, must be a Dict type")
Expand Down Expand Up @@ -169,7 +170,17 @@ def map(self, from_obj, to_type=type(None), ignore_case=False, allow_none=False,

# Currently, all target class data members need to have default value
# Object with __init__ that carries required non-default arguments are not supported
inst = key_to()
if is_dataclass(key_to):
def default_val(v):
if v.default is not MISSING:
return v.default
if v.default_factory is not MISSING:
return v.default_factory()
return None
inst = key_to(**{k: default_val(v) for k, v in key_to.__dataclass_fields__.items()})
else:
inst = key_to()


def not_private(s):
return not s.startswith('_')
Expand Down