Search code examples
pythonreflectionmodulereload

Python reflection after module reloading


I am trying to reflect a module after reloading it. Every time I change the module, I need to reflect it to see its current state. The problem is that it remembers all of its previous states. Here is my code.

main.py

from tkinter import *
from importlib import reload

def fun():
    import second
    reload(second)
    print(dir(second))

root=Tk()
Button(root,text='reload',command=fun).pack()
root.mainloop()

second.py

var1='hello'

When I change the variable name in 'second.py' from 'var1' to 'var2' for example, it prints both variables 'var1' and 'var2'. I need only the latest version of the module (only 'var2').

Thanks for help


Solution

  • importlib.reload updates the module's global namespace, i.e. it retains the old name bindings. If you want a fresh module object, you can remove the old one from sys.modules before importing it:

    def fun():
        sys.modules.pop('second', None)
        import second
        ...