Python module global variable | Example code

To create a module global variable you just need to declare the variable as global in Python. Global variables are also accessible from outside the module by using module_name dot var_name.

Syntax

module_name.var_name

Python module global variable example

Simple example code the only global variables Python really has are module-scoped variables.

Let’s make a module-global variable is just assign to a name.

First, main.py file with variable name msg.

msg = "Hello Main Class"

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

import main
print(main.msg)

Output:

Python module global variable

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.