8000 Add __getitem__ method to DictWrapper by lakam99 · Pull Request #126 · python-amazon-mws/python-amazon-mws · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on Jan 4, 2025. It is now read-only.

Conversation

@lakam99
Copy link
Contributor
@lakam99 lakam99 commented Jul 12, 2019

Add getitem method to allow DictWrapper to be indexed like a normal dictionary

Add __getitem__ method to allow DictWrapper to be indexed like a normal dictionary
@codecov
Copy link
codecov bot commented Jul 12, 2019

Codecov Report

Merging #126 into master will increase coverage by 0.01%.
The diff coverage is 50%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #126      +/-   ##
==========================================
+ Coverage   46.67%   46.68%   +0.01%     
==========================================
  Files           4        4              
  Lines         632      634       +2     
  Branches       64       64              
==========================================
+ Hits          295      296       +1     
- Misses        322      325       +3     
+ Partials       15       13       -2
Impacted Files Coverage Δ
mws/mws.py 44.62% <50%> (+0.02%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update ccef002...74415da. Read the comment docs.

@elcolumbio
Copy link
Contributor

In #75 i have rewritten this is part completely from scratch.
With added functionality for easier and more natural data access (like your intention).
Everything is nested so if you return the values you will get data types which are not so easy to handle.
For example if you are doing dict1['key1'] you want t 8000 o also do key['key1']['key1_1'] which still wouldnt work and make things more confusing.
I thought my new Dotdict handles that part nicely. But we neeed people to try it out and give feedback :).

class DotDict:
"""
A read-only dict like class for navigating a JSON-like object.
x = DotDict(xmltodict(apiresponse))
accessing values:
using attribute notation:
position_in_list = 0
x.key1.nestedkey2[position_in_list]
standard subscriptable like: dict['key'] or list[0]
implemented a get(key, default) function , you can use like:
x.RequestReportResult.get('ReportRequestInfo', 'alt1').EndDate
"""
def __init__(self, mapping):
"""
Instantiate a copy of the passed dictionary from xmltodict.
"""
self.__data = mapping
def __getattr__(self, name):
"""
Run if no attribute has the same name.
Example when not: DotDict(obj).get()
"""
if hasattr(self.__data, name):
# Looks for data attributes like dict.keys()
return getattr(self.__data, name)
else:
# pyhon 2 fix
if name == '__nonzero__':
return None
# it's not an attribute, so use it as a key for the data
return DotDict.build(self.__data[name])
def __getitem__(self, key):
"""
Allow subscription like: dict['key'].
"""
assert isinstance(self.__data, Mapping) is True
return DotDict.build(self.__data[key])
def __repr__(self):
return str(self.__dict__['_DotDict__data'])
def __str__(self):
"""
Pprint is standard printout.
"""
return pprint.pformat(self.__dict__['_DotDict__data'])
def get(self, key, default=None):
"""
Use it like the dictionary get method.
"""
try:
assert isinstance(self.__data, Mapping) is True
return DotDict.build(self.__data[key])
except KeyError:
return default
@classmethod
def build(cls, obj):
"""
Fetch objects. A constructor providing the main functionality.
"""
if isinstance(obj, Mapping):
return cls(obj) # Build a DotDict object
elif isinstance(obj, MutableSequence):
# The dict is from xmltodict, so a MutableSequence must be a list
return [cls.build(item) for item in obj]
else: # If it's not a list or a dict return the item as it is
return obj

@lakam99
Copy link
Contributor Author
lakam99 commented Jul 24, 2019

This is a lot cleaner than the DictWrapper for sure!

@lakam99 lakam99 closed this Jul 24, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0