Is there any way to clear cache bytecode in Python?

each unit test I start writing python code to a file and then import it as a module. The problem is that the code is changing, but additional import statements do not change the module.

I think I need a simple ether to reload the module or clear the internal bytecode cache. Any ideas?

Thanks!

+4
source share
4 answers

Reimport modules are complex to get all edge cases. The documentation for reload mentions some of them. Depending on what you are testing, you might be better off by testing the import using separate interpreter calls, running each of them, say, subprocess . This will probably be slower, but probably safer and more accurate testing.

+8
source

Use reload() .

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

However, the module must already be loaded. The workaround is to process the resulting NameError :

 try: reload(math) except NameError: import math 
+4
source

Write your code on modules with different names. Writing new code to an existing file and attempting to import it will not work again.

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

 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] 
+3
source

In a similar situation. It later became clear that white space indentation matters. Especially on window platforms, make sure that the unified technique is adapted throughout the module, i.e. use only a tab or spaces.

0
source

Source: https://habr.com/ru/post/1335180/


All Articles