Welcome, guest | Sign In | My Account | Store | Cart

When you create a Python module, you can use a test script wich import your module. But you probably have noticed that when you run the test script, it always use the first version of your module even if you made changes in the code. This is because the import statement check if the module is already in memory and do the import stuff only when this is mandated.

You can use the reload() function but this is quite difficult if you do changes in a module wich isn't directly imported by your test script.

A good solution could be to remove all modules from memory before running the test script. You only have to put some few lines at the start of your test script.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#solution1:
import sys
sys.modules.clear()

#solution2:
import sys
if globals().has_key('init_modules'):
	for m in [x for x in sys.modules.keys() if x not in init_modules]:
		del(sys.modules[m]) 
else:
	init_modules = sys.modules.keys()

If you work with a tool like IDLE, you will notice that solution 1 fail. This is because sys.modules.clear() remove IDLE from memory, so you will have to use solution 2 in that case.