Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

In test1.py you could have a function that returns the value of the variable a

defget_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()

deftest_function2():
    print(a)


test_function2()

Solution 2:

Test1.py

def test_function():
    a ="aaa"return a

Test2.py

import test1


def test_function2():
    print(test1.test_function())


test_function2()

Solution 3:

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 *

deftest_function2():
  print(a)


test_function2()

Solution 4:

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()

Solution 5:

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

Post a Comment for "Python Importing Variables From Other File"