
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reloading Modules in Python
The reload() is used to reload 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 made 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.
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.
How to Load a Module
Let's first see how to load a module in Python. Use the import statement to load ?
import importlib
How to Reload a Module
The reload() method is used to reload a module. The argument passed to the reload() must be a module object which is successfully imported before.
import importlib importlib.reload(module)
Example
We are reloading the importlib module ?
import sys import importlib importlib.reload(sys)