Python3 reload() Function

Python 内置函数Python Built-in Functions


Description

reload()Used to reload a previously loaded module.

In Python 2.x,reload()it is a built-in function and can be used directly. SeePython2.x reload() function. InPython2.x ~ Python3.3version, it was moved toimpthe package (Python2.x can also import the imp package to use it), and after Python3.4, it was moved toimportlibthe package.

Syntax

Python2.x ~ versions before Python3.3:

import imp
imp.reload(module)

or

from imp import reload
reload(module)

Python3.4 and later versions:

import importlib
importlib.reload(module)

or

from importlib import reload
reload(module)

Parameters

  • module -- the module object.

Return Value

Returns the module object.

Examples

The following examples demonstrate how to use reload().

Example 1

Reload the sys module

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

Example 2

First, we create a example.py in the current directory:

example.py file

# Test code for example.py file site = "EXAMPLE"

Launch the Python interactive command window in the current directory:

Example

>>>import example >>> example.site 'EXAMPLE'

Then edit the example.py file in another window (do not close the Python interactive command window above), and modify it to the following code:

Modified example.py file

# Test code for example.py file site = "GOOGLE"

Then return to the Python interactive command window:

Example

>>> example.site    # The output remains unchanged
'EXAMPLE'
>>> from importlib import reload  # Python 3.4+
>>> reload(example)    # Reload the modified example.py file
<module 'example' from '/Users/EXAMPLE/example-test/example.py'>
>>> example.site    # The output is now correct
'GOOGLE'

Python 内置函数Python Built-in Functions

Other Extensions