Closed
Description
Expected Behaviour
DictWrapper
and all of its subclasses should fully implement the Mapping interface so that it can be used interchangeably with code that expects the event
to be a dictionary. This helps Powertools Middleware play nicely with existing middleware.
Current Behaviour
DictWrapper
does not implement the abstract __iter__
and __len__
methods from the Mapping
interface. Currently, client code cannot iterate over any subclass of DictWrapper
, nor can it use the dictionary built-ins keys
, values
, or items
.
Code snippet
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
event = DictWrapper({'foo': 'bar'})
[k for k in event] # raises KeyError: 0
# all of the following raise AttributeError: 'DictWrapper' object has no attribute '...'
event.keys()
event.items()
event.values()
Possible Solution
DictWrapper
should subclass either Mapping
or Dict
, for example:
class DictWrapper(Mapping):
"""Provides a single read only access to a wrapper dict"""
def __init__(self, data: Dict[str, Any]):
self._data = data
def __getitem__(self, key: str) -> Any:
return self._data[key]
def __eq__(self, other: Any) -> bool:
if not isinstance(other, DictWrapper):
return False
return self._data == other._data
def get(self, key: str) -> Optional[Any]:
return self._data.get(key)
@property
def raw_event(self) -> Dict[str, Any]:
"""The original raw event dict"""
return self._data
# missing methods
def __iter__(self) -> Iterator:
return iter(self._data)
def __len__(self) -> int:
return len(self._data)
Steps to Reproduce
see comment above
AWS Lambda Powertools for Python version
latest
AWS Lambda function runtime
3.9
Packaging format used
PyPi
Debugging logs
No logs here. I'm happy to submit the PR to fix this. This should be a non-breaking change.