Python global multiple variables | Example code

Set up a variable in the module will work as a global variable you can define multiple variables in the class. The reason for this is that python treats classes as modules.

Python global multiple variables example

Simple example code defines multiple global variables from inside a class.

This is the best way to set up a list of global variables would be to set up a class for them in that module. You can call them, update them, etc. in any other function by referencing them as such:

main.py

class globalBS():
    bsA = "a"
    bsB = "b"

Test.py

from main import globalBS

print(globalBS.bsA)

globalBS.bsB = "Hello"
print(globalBS.bsB)

Output:

Python global multiple variables

Note: The global statement does not create variables. It just makes Python look for them in the global namespace instead of the local namespace.

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.