TransWikia.com

Python: access a variable in a module from another file

Stack Overflow Asked by yeroduk on February 13, 2021

I want to access var1 and var2 in another python file where I will be using the variables in another function. How do I do this?

file1.py

def main(x):
    var1 = "link"
    var2 = "email"

file2.py

from file1 import var1, var2
class test:
    def get_email(self):
        return var2
    def get_link(self):
        return var1

2 Answers

To import variables and methods from another file, you need to initialise init.py and main.py in your folder as empty files. After that you can either declare your variables you want to import on the top(outermost namespace) or return them from a function

A.py

myVar = 1
myString = “help”

def get_variables():
    myVar = 1
    myString = “help”
    return myVar, myString

B.py (first way)

from A import myVar, myString

B.py (second way)

from A import get_variables
myVar, myString = get_variables()

Answered by ATIF ADIB on February 13, 2021

If you want to use those variables in a separate module, you need to have the variables in the top level.

var1 = ....
var2 = ....

def main(x):
    ....

This is because variables inside a function are local to that function and only accessible in it.

If you want to only declare the variables in the top level but assign within the function-

var1 = None
var2 = None

def main(x):
    global var1
    global var2
    # assign here

Remember however, variables assigned within a function will only reflect changes if that function is called. Importing a module will not automatically call the function, unless the function is called at the top level in the imported module-

var1 = None
var2 = None

def main(x):
    global var1
    global var2
    # assign here

# x should be defined prior to this
main(x)

Answered by Chase on February 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP