0

I have a Python script which

  1. calls a function foo which imports and uses module my_module
  2. does some lengthy calculations
  3. calls a function bar which also imports and uses module my_module

If my_module.py is changed at some point during step 2, will bar always use the same my_module that was used in foo ?

What if I run another Python script during step 2. that also imports my_module?

I created the toy scenarios above, and it seems like my_module indeed stays the same for all its calls in the original Pythons script, but I'd like to have a guarantee for that or know situations in which it could fail.

(Background: This is for scientific software development. I write an algorithm, commit to git, run it to see if it works and what it produces, and while waiting for it to finish continue working on its source. If I don't like the results, I'd like to know what exact source was responsible for the results.)

Bananach
  • 2,016
  • 26
  • 51
  • 1
    If you edit the *file*, not unless something explicitly `reload`s the module; it's stored in memory once, when first imported. – jonrsharpe Aug 25 '18 at 13:34
  • Modules are loaded into memory *just once*. It doesn't matter if the source file changed. – Martijn Pieters Aug 25 '18 at 13:35
  • @MartijnPieters Doesn't the question that you listed as duplicate address the opposite problem? I actually had read that other question before, but there, the modules are supposed to be reloaded and the answers provide ways to guarantee that they are. As far as I understood, that does not imply that without importlib.reload the modules are never changed. Anyway, your comment does say so, so thanks for the answer – Bananach Aug 25 '18 at 13:56
  • @Bananach: that post exists *because* modules don't reload on their own. Had there been other paths to reloading (such as editing the source file) those would have been documented there. – Martijn Pieters Aug 25 '18 at 14:13
  • @MartijnPieters There could have been options that do not guarantee a reload but that pose a risk(nonzero chance) of a reload. Those options would have not been suitable as answers there, but they would have been important to about for me – Bananach Aug 25 '18 at 14:16
  • there are no such options. The full process is documented at https://docs.python.org/3/reference/import.html; modules are searched for in `sys.modules` first, if present there then no loading takes place, see [*5.3.1. The module cache*](https://docs.python.org/3/reference/import.html#the-module-cache) – Martijn Pieters Aug 25 '18 at 14:22

0 Answers0