Use the same connection or collection object
If we are using lots of MongoDicts it's better to reuse the same connection for all of them. MongoDict.__init__ should have an option to receive a connection object.
If you have a MongoDB connection in your code, maybe you want to pass only the collection object, so MongoDict.__init__ should accept it as a parameter too.
If the user needs to create more than one MongoDict for the same database, maybe a good idea is to have a class that is a 'pool' of MongoDicts, something like this:
from mongodict import MongoDictPool
pool = MongoDictPool(hostname='localhost', port=27017, database='mydb')
my_dict_1 = pool.new('collection_name_for_dict_1')
my_dict_1['python'] = 'rules' # use it normally, it's a MongoDict instance!
my_dict_2 = pool.new('collection_name_for_dict_2')
my_dict_1['answer'] = 42 # use it normally, it's a MongoDict instance!
It'd be good to accept either pymongo.Connection, Database or even Collection objects - but maybe it's a very specific case - I cleared the milestone (was 0.3.0) from this issue to open it to discussion.
My personal-use hack of MongoDict implements the idea of the Aug 6 2012 post by bring-your-own-connection:
class MongoDict.__init__() has a new connection=None argument and it's self._connection = has a new connection or short circuit to use connection, if provided.
def __init__(self, host='localhost', port=27017, database='mongodict',
connection=None,
collection='main', codec=(pickle_dumps, pickle.loads),
safe=True, auth=None, default=None, index_type='key'):
''' MongoDB-backed Python ``dict``-like interface
Create a new MongoDB connection.
`auth` must be (login, password)'''
super(MongoDict, self).__init__()
self._connection = connection or pymongo.Connection(host=host, port=port, safe=safe)
Example use: If implementor need a "pool" they can do it with a dictionary of MongoDicts like my_pool below.
>>> import pymongo
>>> import mongodict
>>> my_conn= pymongo.Connection(host='localhost', port=27017, safe=True)
>>> my_pool = {}
>>> my_dict = my_pool['store'] =mongodict.MongoDict(connection=my_conn,
database='my_dict', collection='store')
>>> my_dict2 = my_pool['store2'] =mongodict.MongoDict(connection=my_conn,
database='my_other_dict', collection='store2')
I would appreciate this addition to github MongoDict project and would be happy to formally contribute this request via git; but seems too trivial to do formally?