Each module is loaded into memory only once during an interpreter session or during a program run, regardless of the number of times it is imported into a program. If multiple imports occur, the module’s code will not be executed again and again.
Suppose during an interactive session, you have imported a module, and the code of the module is changed while you are using these modules. You might want to use the updated module code by importing it again, but this is not possible since any imports that are done after the first import just use the already loaded module object, the module is not reloaded and its code is not executed again. You have to restart the interpreter session or execute the program again to reload the module. However, you can force a reload by using the reload function from the importlib module. This way we can get the updated version of the already loaded module without exiting the interpreter session.
>>> import module1
>>> from importlib import reload
>>> reload(module1)
zzh@ZZHPC:/zdata/Github/python$ python Python 3.12.3 (main, May 16 2024, 09:18:37) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import aaa >>> f = aaa.Fraction(2, 3) >>> print(f) 2/3 >>> str(f) '2/3' >>> f <aaa.Fraction object at 0x76587b535b50> >>> from importlib import reload Added __repr__ for class Fraction. >>> reload(aaa) <module 'aaa' from '/zdata/Github/python/aaa.py'> >>> f <aaa.Fraction object at 0x76587b535b50> >>> f = aaa.Fraction(2, 3) >>> f Fraction(2,3)
reload的更新对已经存在的变量不起作用。