Python OOP: how to share a MongoDB connection with all classes
<p>I'm working on a <code>Python</code> OOP project. I have to deal with MongoDB interaction but I don't want to use an <code>ODM</code> like <code>mongoengine</code>.</p>

<p>What I want is to share a main Mongo connection with all classes that have to interact with it. I think that using a main DB class could be a good idea and I have two solutions in mind.</p>

<p><strong>Solution A</strong>
Connection at class level</p>

<p>mydb.py</p>

<pre><code>from pymongo import MongoClient

class MyMongoDB(object):

    _client = MongoClient('localhost', 27017)
    db = _client['name_of_the_db']
</code></pre>

<p>And in other classes:</p>

<pre><code>from mydb import MyMongoDB

class Foo(object):

    _db_collection = MyMongoDB.db.foo_collection

    def __init__(self):
       pass

    def set_data(self, data):
       Foo._db_collection.insert_one(data)
</code></pre>

<p><strong>Solution A</strong>
Connection at instance level</p>

<p>mydb.py</p>

<pre><code>from pymongo import MongoClient

class MyMongoDB(object):

    def __init__(self):
        _client = MongoClient('localhost', 27017)
        db = _client['name_of_the_db']
</code></pre>

<p>And in other classes:</p>

<pre><code>from mydb import MyMongoDB

class Foo(object):

    _db_collection = MyMongoDB().db.foo_collection

    def __init__(self):
       pass

    def set_data(self, data):
       Foo._db_collection.insert_one(data)
</code></pre>

<p>In <strong>solution A</strong> I have one main connection even if I import the MongoDB class in a lot of modules.</p>

<p>In <strong>solution B</strong> I have one new instance for each import</p>

<p>I think that <strong>solution A</strong> is the proper way to do the trick. Isn't it? Are they better approaches?</p>