

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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() - 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.
- Related Questions & Answers
- Locating Modules in Python
- XML Processing Modules in Python
- How do Python modules work?
- URL handling Python modules (urllib)
- How to install Python modules in Cygwin?
- XMLRPC server and client modules in Python
- Locating and executing Python modules (runpy)
- Where are the python modules stored?
- How to use remote python modules?
- JavaScript modules
- Can we keep Python modules in compiled format?
- How we can import Python modules in Jython?
- How does variable scopes work in Python Modules?
- Python import modules from Zip archives (zipimport)
- How to check version of python modules?