Even if the import does not run the code several times, this is definitely not the right way.
Instead, you should hide the process of getting the connection or cursor behind the function. You can then implement this function using either the Singleton template or the Object Pool>.
So, it will be something like this:
db.py:
_connection = None def get_connection(): global _connection if not _connection: _connection = MySQLdb.connect(host="localhost"...) return _connection
someothermodule.py:
import db conn = db.get_connection()
By the way, depending on what you are doing, there might not be much good idea to share your connection object, rather than creating a new one every time you need it.
But why do you want to write the get_connection() method to abstract from these problems in the rest of your code.
source share