I have two scripts, first.py and second.py. I want to send variables of first to second and variables of second to first. But it shows an error. Can any one help me please?
first.py
import second
a=10
print second.b
second.py
import first
b=15
print first.a
The error
AttributeError: 'module' object has no attribute 'b'
3 Answers 3
Quite frankly, you don't want to do that. It can lead to circular imports (or partial imports) and lots of confusion. What you normally want is a main program that will import the other two. The main program can then pass data from one to the other since it has access to both.
There is also the idea of Publish / Subscribe - https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
In Python you can do this yourself or you can use a convenient package such as PyPubSub or PyDispatcher
Comments
You can use a simple memcached server for that. https://pypi.python.org/pypi/python-memcached
1 Comment
Alternatively, if it is also something that someone else might benefit from, you can try writing it into a third file(Call it variable.txt or something)
secondinfirst.py, the first thing that happens isfirstis imported tosecond. Then,firstis read, skipping overimport secondsince that's ready happened and Python won't import the same thing twice (otherwise you'd get an infinite loop of imports between the two files). Then the linea=10is read, and finallyprint second.b. The issue is thatsecond.pyhasn't had time to read down to the bottom because it tried toimport firstfirst, and so it hasn't assignedbby the timeprint second.bis called.