0

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.

asked Jul 2, 2014 at 12:11
2
  • You can use list of variables b.baz( [var1, var2] ) or dictionary b.baz( {'var1':7, 'var2':9} ) and then you have to rebuild baz() Commented Jul 2, 2014 at 12:39
  • @furas But then the variables would have to be used as the_variable[7] which is quite unclear. I could pass an instance of a custom class, and do the_variable.var1 which would be better, but I'd still like to avoid that if possible. Commented Jul 2, 2014 at 12:43

1 Answer 1

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.

answered Jul 2, 2014 at 12:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.