5

each unit test I'm running is writing python code out to a file, then importing it as a module. The problem is that the code changes but further import statements don't modify the module.

I think what I need is a way to ether force a reload on a module or clear the internal bytecode cache. Any ideas?

Thanks!

4 Answers 4

8

Reimporting modules is tricky to get all the edge cases right. The documentation for reload mentions some of them. Depending on what you are testing, you may be better off by testing the imports with separate invocations of the interpreter by running each via, say, subprocess. It will likely be slower but also likely safer and more accurate testing.

1
  • I liked this solution the best because it allows the tests to be done with different python interpreters too and it is a lot safer (my tests work now!)
    – Scott
    Jan 12, 2011 at 2:16
4

Use reload().

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).

However, the module needs to be already loaded. A workaround is to handle the resulting NameError:

try:
    reload(math)
except NameError:
    import math
1
  • However, you can only use reload on a module that has already been loaded. I tried this approach, however dir() doesn't list my module as loaded
    – Scott
    Jan 12, 2011 at 1:07
3

Write your code to differently-named modules. Writing new code into an existing file, and trying to import it again will not work well.

Alternatively, you can clobber sys.modules. For example:

class MyTestCase(unittest.TestCase):
    def setUp(self):
        # Record sys.modules here so we can restore it in tearDown.
        self.old_modules = dict(sys.modules)

    def tearDown(self):
        # Remove any new modules imported during the test run. This lets us
        # import the same source files for more than one test.
        for m in [m for m in sys.modules if m not in self.old_modules]:
            del sys.modules[m]
0

Ran into a similar situation. Later on found that the white space indentation technique used matters. Especially on windows platforms, ensure that a uniform technique is adapted throughout the module i.e., either use tab or spaces exclusively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.