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?
Global Constants. A global constant is a literal value to which you assign a name. Like a global variable, you can access the value of the global constant from any script or 4GL procedure in the application. You set the value for the global constant when you declare it.
You can declare Global list on the file/module level like: my_global_list = list() in Python. If you want to append to it inside a function you can use the global keyword.
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(): global GLOBAL_VAR #do something
Or in other modules:
from mymodule import GLOBAL_VAR
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With