0

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

user1763510
  • 1,070
  • 1
  • 15
  • 28
  • Place `foo = ...` in a function, and in `config.py` do the following: `function(moduleToBeImported)`? – Torxed Jun 10 '16 at 19:59
  • 1
    Why are you importing modules this way? Are you trying to create a plugin system? Why can't `file2` simply be installed like normal python modules? – Brendan Abel Jun 10 '16 at 20:57
  • Maybe there is a better way to do this, but I am developing a framework, where I want file1.py to not be updated by the user. The user will create the config.py file and the file2.py file, but won't update the file1.py file. Then to run the program, they can simply run the config.py file which calls functions and classes from the other files. – user1763510 Jun 10 '16 at 21:12

1 Answers1

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?

Community
  • 1
  • 1
Quirk
  • 1,305
  • 4
  • 15
  • 29
  • 2
    Python has import guards. Modules are only imported once. If you imported `config` in `file1` and then `file1` in `config` it would work fine. Most of the issues with circular dependencies are when people try to import specific symbols from a module that won't have been defined when the circular import happens. That said, I agree that the structure in the question doesn't make much sense, and there are probably much better ways to achieve what they want. – Brendan Abel Jun 10 '16 at 21:01
  • Thanks for the comment. Maybe I am missing something, but the file I want to import in file1.py is actually file2.py, so there wouldn't be a circular import. – user1763510 Jun 10 '16 at 21:07