Hubschr
Hubschr

Reputation: 1335

How to import files while running?

I have following Problem:

file1.py has functions and variables wich I need for file2.py. With from file1 import myclass1 there is no problem with that. The problem is, I also want to "send" variables from file2.py to file1.py while running file2.py

from file1 import myclass1 in file2.py doesnt work because when i compile file2.py it apears an ImportError:

pydev debugger: starting
Traceback (most recent call last):

   File "****\file1.py", line 13, in <module>
      from file1 import myclass1
   File "****\forfile1.py", line 7, in <module>
      from file2 import myclass2
   File "****\file1.py", line 13, in <module>
      from file1 import myclass1
ImportError: cannot import name s4dat_class

So, how can u import files, while running? or are there other ways to do what I want? Thx

Upvotes: 0

Views: 73

Answers (2)

Raydel Miranda
Raydel Miranda

Reputation: 14360

in file_2.py you can type:

my_module = __import__("file_1")  # assuming file_1.py in the python path.

then you can use my_module as it was file_1

But in order to achive what you want I recommend you put all those things that are common to file_1.py and file2_py in a separated file file_3.py for instance. Then you can import file_3.py in both.

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

If the question is "how do I import from module1 into module2 when module2 imports from module1", the simple answer is "you can't", and the solution is either

  • merge both modules,
  • or extract the common dependencies into a third module
  • or pass needed objects (hint : classes and functions are objects too) as function or method params (simplest form of dependency injection).

The complete answer is that there are workarounds (like importing from within a function body), but that's fugly and 99.8% of the time (approximately ) a sure design smell - you should not have cyclic dependencies so better to cure the design than resort to fugly workarounds.

Upvotes: 1

Related Questions