pymongo and attribute dictionaries

Ian Kelly ian.g.kelly at gmail.com
Wed Feb 4 15:54:22 EST 2015


On Wed, Feb 4, 2015 at 1:16 PM, Travis Griggs <travisgriggs at gmail.com> wrote:
> Yes, that is clever. So if you wanted to minimize the amount of typing you had to do at all of your pymongo API call sites, what strategy would you use to keep that relatively terse?
>
> Is the following the right approach to take?
>
> class Doc(object):
>     def __init__(self, target):
>         self.__dict__ = target
>
> and then something like
>
> for doc in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}}):
>     pprint(doc)
>
> changes to
>
> for doc in ((Doc(d) for d in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}})):
>     pprint(doc)
>
> Are there other approaches? Feel free to impress me with evil abuses in the interest of academic enrichment...

I'd prefer map (or itertools.imap in Python 2) over the inline
generator in this case:

for doc in map(Doc, client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}})):
    pprint(doc)

Or if you like, a utility function wrapping the same.

def docs(dicts):
    return map(Doc, dicts)



More information about the Python-list mailing list