Skip to content
Advertisement

How do you declare a global constant in Python?

I have some heavy calculations that I want to do when my program starts, and then I want to save the result (a big bumpy matrix) in memory so that I can use it again and again. My program contains multiple files and classes, and I would like to be able to access this variable from anywhere, and if possible define it as constant.

How do you define a global constant in Python?

Advertisement

Answer

You can just declare a variable on the module level and use it in the module as a global variable. An you can also import it to other modules.

#mymodule.py
GLOBAL_VAR = 'Magic String' #or matrix...

def myfunc():
    print(GLOBAL_VAR)

Or in other modules:

from mymodule import GLOBAL_VAR
Advertisement