Python module variables | Example code

The only global variables really have are module-scoped variables in Python. You can’t make a variable that is truly global; a variable can have a particular scope.

Python module variables example

Simple example code to make a module-global variable is just assigned to a name.

Imagine a file called main.py, containing this single line with variable name msg.

msg = "Hello Main Class"

Now imagine you import it into a Test.py and print the value of variable msg.

import main
print(main.msg)

Output: Hello Main Class

How to create module-wide variables in Python?

Use it upper code as same in below complete code structure create and use module variables.

Python module variables

Do comment if you have any doubts and suggestions on these Python variables.

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.