Implement MappingObjects and MutableMappingObjects
This commit is contained in:
parent
7d20e6cd3c
commit
37784170a6
|
@ -0,0 +1,65 @@
|
|||
from typing import (
|
||||
Mapping, MutableMapping, Sequence, Set,
|
||||
Iterable, Iterator, ByteString, Any,
|
||||
)
|
||||
|
||||
|
||||
def objectify(value: Any) -> Any:
|
||||
if isinstance(value, MutableMapping):
|
||||
return MutableMappingObject(value)
|
||||
elif isinstance(value, Mapping):
|
||||
return MappingObject(value)
|
||||
elif isinstance(value, (str, ByteString)):
|
||||
# Do not treat strings and bytestrings as normal sequences
|
||||
return value
|
||||
elif isinstance(value, Sequence):
|
||||
return list(map(objectify, value))
|
||||
elif isinstance(value, Set):
|
||||
return set(map(objectify, value))
|
||||
elif isinstance(value, Iterable):
|
||||
return map(objectify, value)
|
||||
return value
|
||||
|
||||
|
||||
class MappingObject(Mapping):
|
||||
|
||||
def __init__(self, *args: Iterable, **kwargs: Any):
|
||||
for iterable in (*args, kwargs):
|
||||
if isinstance(iterable, Mapping):
|
||||
iterable = iterable.items()
|
||||
for k, v in iterable:
|
||||
setattr(self, k, v)
|
||||
|
||||
def __getitem__(self, name: Any) -> Any:
|
||||
try:
|
||||
attr = getattr(self, name)
|
||||
except AttributeError:
|
||||
raise KeyError(repr(name))
|
||||
return objectify(attr)
|
||||
|
||||
def __iter__(self) -> Iterator:
|
||||
return iter(self.__dict__)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.__dict__)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return '{}({!r})'.format(self.__class__.__name__, self.__dict__)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.__dict__)
|
||||
|
||||
def copy(self) -> 'MappingObject':
|
||||
return self.__class__(self.__dict__)
|
||||
|
||||
|
||||
class MutableMappingObject(MappingObject, MutableMapping):
|
||||
|
||||
def __setitem__(self, name: Any, value: Any) -> None:
|
||||
setattr(self, name, value)
|
||||
|
||||
def __delitem__(self, name: Any) -> None:
|
||||
try:
|
||||
delattr(self, name)
|
||||
except AttributeError:
|
||||
raise KeyError(repr(name))
|
Loading…
Reference in New Issue