Answer the question
In order to leave comments, you need to log in
Global import of modules in Python
How can I make modules imported in a "base" module available to modules importing that "base" module?
Example.
#parent.py
import _mysql
class Parent:
pass
#child.py
import parent
class Child(Parent):
db = _mysql.connect(...
#parent.py
__all__ = ['_mysql']
and do#child.py
from parent import *
But as far as I understand, this is not the most beautiful option. Answer the question
In order to leave comments, you need to log in
from parent import _mysql
. You can also just re-import _mysql
, this will return the already imported module from sys.modules
. In Python, each module has its own namespace, modules do not intersect with each other, and this is considered a feature, not a bug. Importing _mysql
is even more correct if the parent module does not add anything to it - this clearly makes it clear that we are dealing with a common _mysql
, and not with what is called in the parent module _mysql
.
1. When re-importing, the module is taken from the cache, this is not as expensive as it might seem.
2. Explicit is better than implicit. It is much better when you can immediately see where the variable comes from in the file, and not look for how magically something appeared from somewhere.
Names starting with _ are considered private. They are not imported when you write from module import *. This is a thoughtful and specially made feature. So the solution is obvious: don't give non-private modules names starting with _. If the module name cannot be changed, then in parent.py you need to write:
import _mysql as mysql
__all__ = ['_mysql']
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question