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.