Python3 reload() Function
Description
The reload() function is used to reload a previously loaded module.
>
In Python 2.x, reload() was a built-in function and could be used directly, see Python 2.x reload() Function. From Python 2.x to Python 3.3, it was moved to the imp
package (Python 2.x could also import the imp package for use), and from Python 3.4 onwards, it was moved to the importlib
package.
Syntax
Python 2.x to Python 3.3:
import imp
imp.reload(module)
or
from imp import reload
reload(module)
Python 3.4 and later:
import importlib
importlib.reload(module)
or
from importlib import reload
reload(module)
Parameters
- module -- The module object.
Return Value
Returns the module object.
Example
The following example demonstrates the use of reload().
Example 1
Reloading the sys Module
>>> import sys, importlib
>>> importlib.reload(sys)
<module 'sys' (built-in)>
Example 2
First, create a tutorialpro.py
file in the current directory:
tutorialpro.py File
# tutorialpro.py file test code
site = "tutorialpro"
Start a Python interactive command window in the current directory:
Example
>>> import tutorialpro
>>> tutorialpro.site
'tutorialpro'
Then edit the tutorialpro.py
file in another window (do not close the above Python interactive command window) and modify it to the following code:
Modified tutorialpro.py File
# tutorialpro.py file test code
site = "GOOGLE"
Then return to the Python interactive command window:
Example
>>> tutorialpro.site # The output remains unchanged
'tutorialpro'
>>> from importlib import reload # Python 3.4+
>>> reload(tutorialpro) # Reload the modified tutorialpro.py file
<module 'tutorialpro' from '/Users/tutorialpro/tutorialpro-test/tutorialpro.py'>
>>> tutorialpro.site # The output is now correct
'GOOGLE'