So I have two different files somewhat like this:
file1.py
from file2 import *
foo = "bar"
test = SomeClass()
file2.py
class SomeClass :
def __init__ (self):
global foo
print foo
However I cannot seem to get file2 to recognize variables from file1 even though its imported into file1 already. It would be extremely helpful if this is possible in some way.
Importing
file2infile1.pymakes the global (i.e., module level) names bound infile2available to following code infile1— the only such name isSomeClass. It does not do the reverse: names defined infile1are not made available to code infile2whenfile1importsfile2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you’re doing it (if everybody under the Sun forgot the very existence of the constructfrom ... import *, life would be so much better for everybody).Apparently you want to make global names defined in
file1available to code infile2and vice versa. This is known as a “cyclical dependency” and is a terrible idea (in Python, or anywhere else for that matter).So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I’d much rather discuss the many excellent way in which you can avoid such terrible structure.
For example, you could put global names that need to be available to both modules in a third module (e.g.
file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3in bothfile1andfile2, and then usefile3.fooetc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you’re wrong;-).