Python - Changes to imported file do not take effect

TheRealFakeNews picture TheRealFakeNews · Mar 27, 2015 · Viewed 8.3k times · Source

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)

Answer

pberkes picture pberkes · Mar 27, 2015

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 (http://bit.ly/1E97V4n) after the import in test_file, to explicitly force a reload of the module:

  import file
  reload(file)