P
P
petrouv2013-01-02 20:58:40
Python
petrouv, 2013-01-02 20:58:40

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(...

Will throw an error because _mysql is not in the global scope.

You can write
#parent.py
__all__ = ['_mysql']
and do
#child.py
from parent import *
But as far as I understand, this is not the most beautiful option.

Is there an implementation in which it is not necessary to re-import commonly used libraries in "child" modules that "do not pollute" the global scope?
Or is re-importing the right solution?
How to correctly build a hierarchy of modules with inherited classes?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
MikhailEdoshin, 2013-01-02
@petrouv

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 _mysqlis 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.

N
niko83, 2013-01-02
@niko83

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.

N
nochkin, 2013-01-02
@nochkin

#child.py
import parent
db = parent._mysql.connect(…

A
Alexey Huseynov, 2013-01-02
@kibergus

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

Then you don't have to write
__all__ = ['_mysql']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question