Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Changes to imported file do not take effect

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)

like image 369
TheRealFakeNews Avatar asked Mar 27 '15 01:03

TheRealFakeNews


2 Answers

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)
like image 122
pberkes Avatar answered Sep 28 '22 10:09

pberkes


With Python 2.x, @pberkes' answer works. For the other Python versions, you may want to see this answer to another SO post.

like image 40
laylaylom Avatar answered Sep 28 '22 10:09

laylaylom