From 4b23b96c6d356f442e3bf596d1d000a120641094 Mon Sep 17 00:00:00 2001 From: Alexey Velikiy Date: Tue, 16 Apr 2019 19:45:05 +0300 Subject: [PATCH] JSONClass --- analytics/analytics/utils/meta.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/analytics/analytics/utils/meta.py b/analytics/analytics/utils/meta.py index 64b9f69..e811880 100644 --- a/analytics/analytics/utils/meta.py +++ b/analytics/analytics/utils/meta.py @@ -1,7 +1,13 @@ from inspect import signature, Parameter from functools import wraps +from typing import Optional +from re import match +def is_field_private(field_name: str) -> Optional[str]: + m = match(r'_[^(__)]+__', field_name) + return m is not None + def inited_params(target_init): target_params = signature(target_init).parameters.values() if len(target_params) < 1: @@ -34,17 +40,15 @@ def JSONClass(target_class): returns a json representation of the class where all None - values and private fileds are skipped """ - private_prefix = '__' - result = { + return { k: v for k, v in self.__dict__.items() - if v is not None and not k.startswith(private_prefix) + if v is not None and not is_field_private(k) } - return result def from_json(json_object: dict) -> target_class: return target_class(**json_object) - target_class.__init__ = inited_params(target_class.__init__) + # target_class.__init__ = inited_params(target_class.__init__) target_class.to_json = to_json target_class.from_json = from_json return target_class