How do you declare a global constant in Python?

Question:

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?

Asked By: cjm2671

||

Answers:

There is no way to declare a constant in Python. You can just use

SOME_CONSTANT = [...]

If the file name where it is declared is file1.py, then you can access to it from other files in the following way:

import file1

print file1.SOME_CONSTANT

Assuming that both files are in the same directory.

Answered By: Christian Tapia

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
Answered By: Mátyás Kuti

I am not sure what you mean by ‘global constant’; because there are no constants in Python (there is no “data protection”, all variables are accessible).

You can implement a singleton pattern, but you will have to regenerate this at runtime each time.

Your other option will be to store the results in an external store (like say, redis) which is accessible from all processes.

Depending on how big your data set is, storing it externally in a fast K/V like redis might offer a performance boost as well.

You would still have to transform and load it though, since redis would not know what a numpy array is (although it has many complex types that you can exploit).

Answered By: Burhan Khalid

I do not think the marked as good answer solves the op question. The global keyword in Python is used to modify a global variable in a local context (as explained here). This means that if the op modifies SOME_CONSTANT within myfunc the change will affect also outside the function scope (globally).

Not using the global keyword at the begining of myfunc is closer to the sense of global constant than the one suggested. Despite there are no means to render a value constant or immutable in Python.

Answered By: SpKel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.