I have 3 files in the same directory : test1.py , test2.py and init.py.
In test1.py I have this code:
def test_function():
a = "aaa"
In test2.py I have this code:
from test1 import *
def test_function2():
print(a)
test_function2()
I can import "test_function" (and call the function) into test2.py but i cannot use the variable "a" in test2.py .
Error : Unresolved reference "a" .
I would like to know if it possible to use "a" inside test2.py .
-
I tried making the variable "a" global in "test_function" but it didn't work , I tried making it global in "test_function2" but it said variable not defined at module level.user11574227– user115742272019年06月09日 18:29:03 +00:00Commented Jun 9, 2019 at 18:29
-
test1.py is invalid (you wanted the 2nd line indented)?CristiFati– CristiFati2019年06月09日 18:37:14 +00:00Commented Jun 9, 2019 at 18:37
-
sorry mistake when pasting codeuser11574227– user115742272019年06月09日 18:40:05 +00:00Commented Jun 9, 2019 at 18:40
6 Answers 6
In test1.py you could have a function that returns the value of the variable a
def get_a():
return a
And when you're in test2.py you can call get_a().
So in test2.py do this to essentially move over the value of a from test1.py.
from test1 import *
a = get_a()
def test_function2():
print(a)
test_function2()
Test1.py
def test_function():
a = "aaa"
return a
Test2.py
import test1
def test_function2():
print(test1.test_function())
test_function2()
What are the rules for local and global variables in Python?¶
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
So make the variable a global and call test_function() in test1 module so that it makes a as global variable while loading modules
test1.py
def test_function():
global a
a = "aaa"
test_function()
test2.py
from test1 import *
def test_function2():
print(a)
test_function2()
Comments
a is only defined in the scope of test_function(). You must define it outside the function and access it using the global keyword. This is what it looks like:
test1.py
a = ""
def test_function():
global a
a = "aaa"
test2.py
import test1
def test_function2():
print(test1.a)
test1.test_function()
test_function2()
Comments
test1.py's code will be this.
def H():
global a
a = "aaa"
H()
and test2.py's code will be this.
import test1 as o
global a
o.H()
print(o.a)
This will allow you to call test one H
Comments
Your code works perfect (with 'a' defined outside out the test1_function), was able to print 'a'. So try the following : 1. Make sure it is a global variable in test1. 2. Import test1 in an interactive session and find out the bug. 3. Double check the environment setup.
Thanks ! :)