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.
JavaScript
x
6
1
#mymodule.py
2
GLOBAL_VAR = 'Magic String' #or matrix...
3
4
def myfunc():
5
print(GLOBAL_VAR)
6
Or in other modules:
JavaScript
1
2
1
from mymodule import GLOBAL_VAR
2