How to reload imported modules after editing Win 6 SR21

Hey there,

just wanted to add a solution I came up with in case the reload() is to restricted. That is the case, for example, if the script you imported is referencing another script (i.e. inheritance) and both are continuously changing during development.

Say you have a file a.py with class A() and a file b.p with a class B(A): and in your script you do:

from b import B
reload(b)
myobj = B()

Here, the reload() will not suffice when changes in file a.py occur and this setting is very common if you develop a whole set of external methods in a well structured way.

Now, here’s the solution. You create a package or namespace (i.e.) a folder with all your files. Say project and reference your files via from project.a import A . A full reset of all modules in that project folder can be achieved by putting the following in your code, before any other imports:

import sys
to_delete = list()
for module in sys.modules:
   if "project" in module:
      to_delete.append(module)  # add them to a list to avoid "dict-size changed during iteration" error

for module in to_delete:
    sys.modules.pop(module)

Hope this is useful for anyone.

2 Likes