Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mutually share variables between two python scripts?

Tags:

python

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'

like image 826
midhun gopi Avatar asked Mar 12 '26 10:03

midhun gopi


1 Answers

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

like image 122
Mike Driscoll Avatar answered Mar 14 '26 23:03

Mike Driscoll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!