Skip to content

Global constants in Python

  • by

Python Global constants can declare a variable on the module level and use it in the module as a global variable. You can also import it to other modules.

Example of defining a global constant using uppercase letters and underscores:

MAX_VALUE = 100

Global constants in Python example

Simple example code.

mymodule.py

GLOBAL_VAR = 'Magic String'


def myfunc():
print(GLOBAL_VAR)

main.py

from mymodule import GLOBAL_VAR

print(GLOBAL_VAR)

Output:

Global constants in Python

How to set global const variables in python?

Answer: You can’t define constants in Python. If you find some sort of hack to do it, you would just confuse everyone.

To do that sort of thing, usually, you should just have a module – globals.py for example you import everywhere that you need it.

Do comment if you have any doubts or suggestions on this Python constant topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading