Reputation: 79
Got 2 files:
First is called: main.py
import side
var = 1
side.todo()
Second is called: side.py
import main
def todo():
print "printing variable from MAIN: %s" %(main.var)
I get an error, when i run main.py:
AttributeError: 'module' object has no attribute 'todo'
In python are you not allowed to borrow and use variables, in such manner?
I have tried to search for documentation related to this, but could not find anything related to this problem.
Surely, there is an alternate way of doing this?
Upvotes: 1
Views: 2151
Reputation: 10761
A fast and ugly solution is to move the import statement to where it will not be executed until it is needed in side.py
def todo():
import main
print "printing variable from MAIN: %s" %(main.var)
I would advice against it though. The example is contrived, but I'm sure you can find a nicer solution to your specific case.
Upvotes: 0
Reputation: 798576
The problem is not "you can't have cyclic imports", it's that you can't use a name before it's defined. Move the call to side.todo()
somewhere it won't happen as soon as the script is run, or move main.var
into a third module.
Upvotes: 2