1

If the main python program first initializes a set of modules and then waits to run their def Run() functions when will it recompile the modules if changed?

Consider the example below...

main script

import mod_a
import mod_b
import mod_c

a = mod_a(<arg>)
b = mod_b(<arg>)
c = mod_c(<arg>)

list_to_run = [a, b, c]

for module in list_to_run:
    module.Run()

Assume mod_a.Run() and mod_b.Run() take some time to run.

I start the main script.

While mod_a.Run() is running I make a change in mod_c.Run() and delete the mod_c.pyc file.

When it comes time for the main script to call mod_c.Run() will it recompile and incorporate the change?

jayare
  • 45
  • 4
  • 2
    Does this answer your question? [How do I unload (reload) a module?](https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-module) – metatoaster Mar 13 '20 at 11:39
  • 1
    In short, no, your code will have to explicitly reload the module before any changes made to the original `py`/`pyc` file(s) are incorporated into the currently running environment. – metatoaster Mar 13 '20 at 11:41

1 Answers1

3

Compilation happens on import. Once you import it, you can even delete the source file and it'll still work.

(2) % ls
foo.py
(2) % cat foo.py
def display():
    print ("Hello, world")
(2) % python
Python 3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
[3.5.2] >>> import foo # Imports foo
[3.5.2] >>> # Now the file is also compiled and stored in __pycache__
[3.5.2] ...
[3.5.2] >>> import shutil
[3.5.2] >>> shutil.rmtree("__pycache__")
[3.5.2] >>> import os
[3.5.2] >>> os.unlink("foo.py")
[3.5.2] >>> # Hit Ctrl-Z here to suspend the interpreter
zsh: suspended  python
-148-(3) % ls # No files here. Everything is deleted
(3) % fg
[3]  - continued  python


[3.5.2] >>> foo.display()
Hello, world
[3.5.2] >>> # Still works.
Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
  • Does the program continue to function because the bytecode is already loaded into RAM? Any further explanation to this would be appreciated - I assumed everything would explode after deleting the pyc files. – byxor Mar 13 '20 at 11:45
  • 2
    Yes. Once you import, the code is compiled and loaded into memory. After that, you don't need the source anymore for the current process. Syntax errors (which occur during compilation) are raised at import time. Not when you actually run stuff. – Noufal Ibrahim Mar 13 '20 at 11:46