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.
Metadata
Metadata
Assignees
Labels
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
rubenfonseca commentedon Sep 12, 2022
Hi @Tankanow thank you for the very clear explanation! Would you mind opening a PR with the changes, together with a couple of tests? We will be thrilled to review it and include it in our next release.
Tankanow commentedon Sep 12, 2022
@rubenfonseca, happy to do so. I'll get to it this week. 👍🏽
github-actions commentedon Oct 5, 2022
This is now released under 1.30.0 version!