Reputation: 139
I have a project with many Python files. There are certain number of variables in some files which I like to use in other files. For example, if
var=10
is defined in f1.py
, what are the ways I can call/use "var"
in other files without using from f1 import var
?
I tried using global
but it doesn't work across all the files.
Thank you!
Upvotes: 0
Views: 336
Reputation: 528
Most of the times I encounter this problem I use different methods:
So when the program starts this class is instantiated and after that passed to the different modules. This also makes it flexible in that when you add an extra field to the class, no parameters need to be changed.
class session_info:
def __init__(self, shared_field1=None, shared_field2=None ....):
self.shared_field1 = shared_field1
self.shared_field2 = shared_field2
def function1(session):
session.shared_field1 = 'stilton'
def function2(session):
print('%s is very runny sir' % session.shared_field1)
session = session_info()
function1(session)
function2(session)
Should print: "stilton is very runny sir"
Upvotes: 0
Reputation: 22453
Declare all of your global variables in one file i.e. my_settings.py
and then import
that in your other scripts.
See this question and it's accepted answer for details: Using global variables between files in Python
Upvotes: 2
Reputation: 31682
You could do it with namescope:
import f1
print(f1.var)
10
f1.var = 20
Then it should change var
in all files which are using that variable with import
.
Upvotes: 1