I have this situation:
library_file1.py:
class A:
def foo(self):
print("bar")
def baz(self):
pass
project_file.py:
from library_file1 import A
class B(A):
def baz(self):
print(the_variable)
library_file2.py:
from project_file import B
the_variable = 7
b = B()
b.foo() # prints "bar"
b.baz() # I want this to print "7", but I don't know how
How do I allow code to be written in project_file.py that can access variables from library_file2.py? The only solution I can think of is this:
project_file.py:
from library_file1 import A
class B(A):
def baz(self, the_variable):
print(the_variable)
library_file2.py:
from project_file import B
the_variable = 7
b = B()
b.foo()
b.baz(the_variable)
but this feels awkward and doesn't scale to many variables like the_variable.
1 Answer 1
Quite easy: you need the variable to be in project_file.py instead of library_file2.py.
Change project_file to:
from library_file1 import A
the_variable = None
class B(A):
def baz(self):
print(the_variable)
And then in library_file2:
import project_file
from project_file import B
project_file.the_variable = 7
b = B()
b.foo() # prints "bar"
b.baz() # prints "7"
Using an argument is also a good solution (you should avoid globals as much as you can).
There is no such a thing as a truly global variable in python. Variables are always attached to a scope. We usually say that a variable is "global" when it's in the module scope.
The widest scope is the built-in scope, so it would be theoretically possible for you to add something as a built-in. However this is a really bad practice. Also it doesn't complete fix the problem, because all files could access that new built-in, but they couldn't re-assign it without explicitly mentioning the scope.
b.baz( [var1, var2] )or dictionaryb.baz( {'var1':7, 'var2':9} )and then you have to rebuildbaz()the_variable[7]which is quite unclear. I could pass an instance of a custom class, and dothe_variable.var1which would be better, but I'd still like to avoid that if possible.