简体   繁体   中英

importing variables across modules

Fairly new to python, have looked around on various so sources, but so far nothing has made the code actually function. The code I am using is from file1 import x . (have also tried import file1.x ) but both of them make the module run rather than giving me the variable. Is there any other code to use or am I missing something?

You need to know that a module is evaluated when you import it, even if you import only one object.

So if you want to avoid this you can hide every running functions inside a statement like :

# in file1.py
x = 1

if __name__ == '__main__':
    running_function(x)
    running_function2(x)

You can declare your variables freely, but you should wrap everything else inside functions or classes, and make the calls inside this special block.

My file1.py has only following line, x="hello world"

from file1 import x

print x actually printing the value from other file1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM