Jorge Leitao
Jorge Leitao

Reputation: 20123

At which point changing a file changes the execution's outcome?

Say I have a module foo.py, with some code, and a script main.py that includes foo and is executed with python -m main.

At which point changing the code of foo affects the outcome of python -m main?

Specifically, does calling import "freeze" the file in the sense that future execution is not affected by changing it?

Example of main.py:

input()
import foo
input()
import foo
print(foo.f())

On which circumstances the modification of a module file can affect the outcome of the execution?

My question is related with the following:

If I have a code under version control and run it, and checkout a different branch, the code from the different branch will be run if some import is called lazily (e.g. on a function to avoid circular depedencies). Is this true?

Upvotes: 1

Views: 43

Answers (2)

ash
ash

Reputation: 5539

From the documentation:

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement.

So changing the module on disk will not have any effect once the module has been imported once. You can see this yourself: have a file foo.py that prints "foo" when imported:

print("foo")

and a file main.py that imports foo multiple times:

import foo
import foo
import foo

and you can see that when you run main.py, the output is only one foo, so foo.py only runs once.

(Note that there is a function importlib.reload that attempts to reload the module, but it is not guaranteed to replace all references to the old module.)

With regard to your edit, yes, that's correct.

Upvotes: 1

Netwave
Netwave

Reputation: 42698

In python documentation

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it.

Once this object is created it will be used even if in another module is reimporting it, python keeps track of already imported modules. If you want to reload them you have to do it manually, check the built-in reload for python2 or imp.reload for python3

Upvotes: 0

Related Questions