Python - Changes to imported file do not take effect
Asked Answered
C

2

10

I have a file called test_file, which is designed to test another file, called file. 'test_file' also contains a .txt file in the same directory. When I update file, save, select 'Change to Editor Directory...', then run test_file, Enthought does not seem to recognize that file was updated. Initially I thought I had to select the 'Change to Editor Directory' option every time I updated file, and so I did, but test_file was still printing 'success', even after I deliberately edited file so that test_file should print false. (Yes, I'm sure that it should have printed false as I added a bunch of gibberish code into file, and even code that shouldn't run, such as throwing in return statements with blatantly incorrect indentation). So, essentially, Enthought Canopy isn't realizing that I've updated file.

However, if I save and quit everything, reopen Enthought, select 'Change to Editor Directory', then run test_file, it prints the correct outcome.

This is very frustrating, because I spent days debugging correct code before I realized this. It has me very concerned because I don't know if what I tested in the past is actually correct, and I don't want this to happen in the future.

What is the possible cause of this? (Note: I don't know if this is an Enthought issue or a Python issue)

Cocklebur answered 27/3, 2015 at 1:53 Comment(0)
H
9

It's hard to say without seeing the code, but I suspect that file is being imported with a command equivalent to import file. Python caches imported modules, and so it would not pick up the changes in file. This is a Python feature, and is independent of Enthought Canopy.

If that's the case, you can solve the problem by adding a call to reload (https://docs.python.org/2/library/functions.html#reload) after the import in test_file, to explicitly force a reload of the module:

  import file
  reload(file)
Hamilton answered 27/3, 2015 at 8:22 Comment(1)
Agreed. For details, see this knowledge base articleMaxson
S
4

With Python 2.x, @pberkes' answer works. For Python 3, you can proceed as follows:

For Python versions >= 3.4:

import importlib
importlib.reload(module)

For Python versions 3.0–3.3:

import imp
imp.reload(module)

source

Sargassum answered 29/3, 2019 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.