Skip to content Skip to sidebar Skip to footer

How Can I Access A Global Variable From Another .py File In Python?

I created two files, and when I run a.py, result is {'1': '1'}, it's correct. however, running b.py, the result is none. How can I get the value of requests from b.py? a.py: reque

Solution 1:

if __name__ == "__main__": means that the code following it will only be executed when the file is called explicitly with python3 filename.py from the command line. Since you are simply importing your file and not executing it, the global variable is never set.

Also, python variables are all "global" variables when declared outside of a function, and the global keyword is only needed when you want to declare a global variable inside of a function.

To fix this, change a.py to the following:

requests = {}

defset_vale():
    requests["1"] = "1"

set_vale()

Post a Comment for "How Can I Access A Global Variable From Another .py File In Python?"