Reloading modules in Python?

PythonServer Side ProgrammingProgramming

The reload() - reloads a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have mades changes to the code. In that scenario we need to make sure that modules are reloaded.

The argument passed to the reload() must be a module object which is successfully imported before.

Syntax

import importlib
importlib.reload(sys)

Example

>>> import sys
>>> import importlib
>>> importlib.reload(sys)
<module 'sys' (built-in)>

However, if you are trying to reload a module which is not imported before, you might get an Error.

>>> import importlib
>>> importlib.reload(sys)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
importlib.reload(sys)
NameError: name 'sys' is not defined

Few points to understand, when reload() is executed -

  • Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the loader which originally loaded the module. However, the init function of the modules is not loaded again

  • The old objects are only reclaimed after their reference counts comes down to zero.

  • The names in the module namespace is changed to new object if any.

  • Other references of the old objects (like names external to the module) are not necessarily refers to the new objects and must be updated in each namespace where they occur if that is required.

raja
Published on 30-Apr-2019 16:15:25
Advertisements