Skip to content

Commit

Permalink
fix(utility): fix KeyError when the "_attrs_base.key" is not None
Browse files Browse the repository at this point in the history
PR Closed: #633
  • Loading branch information
zhen.chen authored and AChenQ committed May 31, 2021
1 parent e619b9e commit 859399a
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions tensorbay/utility/attr.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class BaseField: # pylint: disable=too-few-public-methods
"""

def __init__(self, key: str) -> None:
def __init__(self, key: Optional[str]) -> None:
self.loader: _Callable
self.dumper: _Callable
self.key = key
Expand Down Expand Up @@ -162,7 +162,8 @@ def _loads(self, contents: Dict[str, Any]) -> None:
"""
base = getattr(self, _ATTRS_BASE, None)
if base:
base.loader(self, contents)
value = contents if base.key is None else contents[base.key]
base.loader(self, value)

for name, field in self._attrs_fields.items():
if field.is_dynamic and field.key not in contents:
Expand All @@ -187,7 +188,7 @@ def _dumps(self) -> Dict[str, Any]:
contents: Dict[str, Any] = {}
base = getattr(self, _ATTRS_BASE, None)
if base:
contents[base.key] = base.dumper(self)
_key_dumper(base.key, contents, base.dumper(self))

for name, field in self._attrs_fields.items():
if field.is_dynamic and not hasattr(self, name):
Expand All @@ -197,10 +198,7 @@ def _dumps(self) -> Dict[str, Any]:
if value == field.default:
continue

if field.key is None:
contents.update(field.dumper(value))
else:
contents[field.key] = field.dumper(value)
_key_dumper(field.key, contents, field.dumper(value))
return contents


Expand Down Expand Up @@ -232,7 +230,7 @@ def attr(
return Field(is_dynamic, key, default, error_message)


def attr_base(key: str) -> Any:
def attr_base(key: Optional[str] = None) -> Any:
"""Return an instance to identify base class fields.
Arguments:
Expand Down Expand Up @@ -271,6 +269,13 @@ def camel(name: str) -> str:
return f"{mixed[0].lower()}{mixed[1:]}"


def _key_dumper(key: Optional[str], contents: Dict[str, Any], value: Any) -> None:
if key is None:
contents.update(value)
else:
contents[key] = value


def _get_operators(annotation: Any) -> Tuple[_Callable, _Callable]:
"""Get attr operating methods by annotations.
Expand Down

0 comments on commit 859399a

Please sign in to comment.