Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 781
cjm2671 Avatar asked Jun 10 '14 06:06

cjm2671


People also ask

What is 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.

How do you declare a global list in Python?

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.


1 Answers

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 
like image 62
Mátyás Kuti Avatar answered Oct 16 '22 13:10

Mátyás Kuti