The Python MongoDB driver, PyMongo
, returns results as dictionaries. I'm trying to figure out the best way to use such a dictionary in an object constructor.
Keep the dictionary as an attribute
self.dict = building_dict
Then each property of the building would be reachable through
building.dict["property"]
.A better attribute name could be used. Maybe a one-letter attribute. This doesn't look so elegant.
Parse dictionary to create attributes
self.name = building_dict['name'] self.construction_date = building_dict['construction_date'] ...
In my model, the dictionaries can be pretty big but this task can be automated in the constructor to perform actions/checks on the values before or after the assignment.
Edit: The use of getters/setters is independent of options 1. and 2. above.
In solution 2., I'd avoid name collision between attributes and their getters by prefixing all dictionary keys by an underscore before making them attributes.
As a side-issue, the dictionary may contain the description of embedded documents, so the constructor should go through the whole dictionary to seek embedded documents that have their specific class in the code and instantiate those classes right away.
Update
I'll most probably use an ODM
such as MongoEngine
for my project and it will deal with those issues.
Outside of this specific use case (link with MongoDB
, existing ODM
s,...), the question is still relevant so I'm leaving below the best answer I could come up with.