Reloading Python Module

Posted by Afsal on 04-Nov-2022

Hi Pythonistas!

Today we will learn a simple trick: reloading a python module. For that, we are using the importlib package.

Consider the example we have a module called reload_module_testing with a function helloworld.

Code

def helloworld():
    return "Hello world"

Then I open the python interpreter

>>> import reload_module_testing
>>> reload_module_testing.helloworld()
'Hello world'
>>>

Then I changed the code of the hellowolrd program

Code

def helloworld():
    return "Hello world reload"

Then run the  helloworld without restarting the interpreter

>>> reload_module_testing.helloworld()
'Hello world'
>>>

Without restarting the changes will not reflect. Using importlib we can bring this change without restating the interpreter. Let see how

Code

>>> from importlib import reload
>>> reload(reload_module_testing)
<module 'reload_module_testing' from '/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/reload_module_testing.py'>
>>> reload_module_testing.helloworld()
'Hello world reload'
>>>

Now we can see that these changes are reflected without restarting the interpreter.

I hope you have learned something from this post. Please share your valuable feedback with afsal@parseltongue.co.in