Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python importing variables from other file

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 .


1 Answers

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()
like image 145
julian mentasti Avatar answered Jan 02 '26 18:01

julian mentasti



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!