Import module defined in another module

2019-09-09 14:16发布

问题:

I have the following setup. The first file (config.py) defines a path, that tells file1.py which module to import.

#file:config.py
moduleToBeImported="/here/is/some/path/file2.py"
import file1

Then in file1.py, I import the module that is defined in config.py

#file:file1.py
import imp
foo = imp.load_source('module.name',moduleToBeImported)

Is it possible to pass the variable moduleToBeImported from config.py to file1.py?

In the current setup I get expected error: NameError: name 'moduleToBeImported' is not defined

回答1:

Short Answer - NO


Long Answer - Maybe, you can. And NO, you shouldn't. Circular imports would result in import cycles. And that is bad.

For example, let's say you imported config.py in file1.py. As soon as you run file1.py and it calls up config.py, the code in config.py runs just like any other python file. At this point, you would end up trying to import file1.py from file1.py.

Python may or may not detect this cycle before it breaks havoc on your system.

Generally speaking, circular imports are a very bad coding practice.


What you can do instead - Your config.py should contain bare minimal runnable code. Instead keep all configuration variables and settings and general utility methods in there. In short, if file1.py contains critical code, it shouldn't be imported into config.py. You can import config.py in file1.py though.

More reading here: Python circular importing?