2

Is it safe to assume that python module is calculated once? If module A contains CONST_A = json.load(...) and is imported multiple times in different files of the same program and different threads, will it be calculated/executed just once? If not, when the CONST_A be recalculated? And would the next structure fix it?

module CALCULATE_CONST_A
    import json
    CONST_A = json.load(open(...))

module A
    from CALCULATE_CONST_A import CONST_A

further imports of A...

Final question: What are the best practices for creating precalculated constants?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Sadderdaze
  • 304
  • 3
  • 14

1 Answers1

2

Well, let's experiment:

tbi.py

print("Hello, World!")

file1.py

import tbi
print("This is file1")

file2.py

import file1
import tbi
print("This is file2")

And now, when we run file2, we see:

$ python file2.py
Hello, World!
This is file1
This is file2

So the answer to your question is yes, python modules are executed once only. If tbi.py were executed twice, we would have seen "Hello World" printed twice. It's logical, then, to conclude that the attributes of the file are set the first time that file is imported.

Furthermore, more experimentation can show you that, if I put a global variable in tbi, and both file1 and file2 modified it, they would both be modifying the same object. This is visible in a number of built-in packages: for example, changing the value of sys.stdout (the file descriptor for standard output, and a global variable specified when the sys module is first loaded) changes it for the entire program, not just the file that modified it.


If you're worried about this sort of thing causing errors, the best thing to do is to not use global variables - instead, use classes and assign them default values when constructed.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53