Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3fe35e6

Browse files
committed
Issue #18193: Add importlib.reload(), documenting (but not
implementing in code) the deprecation of imp.reload(). Thanks to Berker Peksag for the patch.
1 parent 6f10576 commit 3fe35e6

6 files changed

Lines changed: 122 additions & 24 deletions

File tree

Doc/library/imp.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,9 @@ This module provides an interface to the mechanisms used to implement the
171171
the class does not affect the method definitions of the instances --- they
172172
continue to use the old class definition. The same is true for derived classes.
173173

174+
.. deprecated:: 3.4
175+
Use :func:`importlib.reload` instead.
176+
174177

175178
The following functions are conveniences for handling :pep:`3147` byte-compiled
176179
file paths.

Doc/library/importlib.rst

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,73 @@ Functions
115115

116116
.. versionadded:: 3.3
117117

118+
.. function:: reload(module)
119+
120+
Reload a previously imported *module*. The argument must be a module object,
121+
so it must have been successfully imported before. This is useful if you
122+
have edited the module source file using an external editor and want to try
123+
out the new version without leaving the Python interpreter. The return value
124+
is the module object (the same as the *module* argument).
125+
126+
When :func:`.reload` is executed:
127+
128+
* Python modules' code is recompiled and the module-level code re-executed,
129+
defining a new set of objects which are bound to names in the module's
130+
dictionary by reusing the :term:`loader` which originally loaded the
131+
module. The ``init`` function of extension modules is not called a second
132+
time.
133+
134+
* As with all other objects in Python the old objects are only reclaimed
135+
after their reference counts drop to zero.
136+
137+
* The names in the module namespace are updated to point to any new or
138+
changed objects.
139+
140+
* Other references to the old objects (such as names external to the module) are
141+
not rebound to refer to the new objects and must be updated in each namespace
142+
where they occur if that is desired.
143+
144+
There are a number of other caveats:
145+
146+
If a module is syntactically correct but its initialization fails, the first
147+
:keyword:`import` statement for it does not bind its name locally, but does
148+
store a (partially initialized) module object in ``sys.modules``. To reload
149+
the module you must first :keyword:`import` it again (this will bind the name
150+
to the partially initialized module object) before you can :func:`reload` it.
151+
152+
When a module is reloaded, its dictionary (containing the module's global
153+
variables) is retained. Redefinitions of names will override the old
154+
definitions, so this is generally not a problem. If the new version of a
155+
module does not define a name that was defined by the old version, the old
156+
definition remains. This feature can be used to the module's advantage if it
157+
maintains a global table or cache of objects --- with a :keyword:`try`
158+
statement it can test for the table's presence and skip its initialization if
159+
desired::
160+
161+
try:
162+
cache
163+
except NameError:
164+
cache = {}
165+
166+
It is legal though generally not very useful to reload built-in or
167+
dynamically loaded modules (this is not true for e.g. :mod:`sys`,
168+
:mod:`__main__`, :mod:`__builtin__` and other key modules where reloading is
169+
frowned upon). In many cases, however, extension modules are not designed to
170+
be initialized more than once, and may fail in arbitrary ways when reloaded.
171+
172+
If a module imports objects from another module using :keyword:`from` ...
173+
:keyword:`import` ..., calling :func:`reload` for the other module does not
174+
redefine the objects imported from it --- one way around this is to
175+
re-execute the :keyword:`from` statement, another is to use :keyword:`import`
176+
and qualified names (*module.name*) instead.
177+
178+
If a module instantiates instances of a class, reloading the module that
179+
defines the class does not affect the method definitions of the instances ---
180+
they continue to use the old class definition. The same is true for derived
181+
classes.
182+
183+
.. versionadded:: 3.4
184+
118185

119186
:mod:`importlib.abc` -- Abstract base classes related to import
120187
---------------------------------------------------------------

Lib/imp.py

Lines changed: 5 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
from importlib import _bootstrap
2525
from importlib import machinery
26+
import importlib
2627
import os
2728
import sys
2829
import tokenize
@@ -246,31 +247,12 @@ def find_module(name, path=None):
246247
return file, file_path, (suffix, mode, type_)
247248

248249

249-
_RELOADING = {}
250-
251250
def reload(module):
252-
"""Reload the module and return it.
251+
"""**DEPRECATED**
252+
253+
Reload the module and return it.
253254
254255
The module must have been successfully imported before.
255256
256257
"""
257-
if not module or type(module) != type(sys):
258-
raise TypeError("reload() argument must be module")
259-
name = module.__name__
260-
if name not in sys.modules:
261-
msg = "module {} not in sys.modules"
262-
raise ImportError(msg.format(name), name=name)
263-
if name in _RELOADING:
264-
return _RELOADING[name]
265-
_RELOADING[name] = module
266-
try:
267-
parent_name = name.rpartition('.')[0]
268-
if parent_name and parent_name not in sys.modules:
269-
msg = "parent {!r} not in sys.modules"
270-
raise ImportError(msg.format(parentname), name=parent_name)
271-
return module.__loader__.load_module(name)
272-
finally:
273-
try:
274-
del _RELOADING[name]
275-
except KeyError:
276-
pass
258+
return importlib.reload(module)

Lib/importlib/__init__.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""A pure Python implementation of import."""
2-
__all__ = ['__import__', 'import_module', 'invalidate_caches']
2+
__all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']
33

44
# Bootstrap help #####################################################
55

@@ -11,6 +11,7 @@
1111
# initialised below if the frozen one is not available).
1212
import _imp # Just the builtin component, NOT the full Python module
1313
import sys
14+
import types
1415

1516
try:
1617
import _frozen_importlib as _bootstrap
@@ -90,3 +91,34 @@ def import_module(name, package=None):
9091
break
9192
level += 1
9293
return _bootstrap._gcd_import(name[level:], package, level)
94+
95+
96+
_RELOADING = {}
97+
98+
99+
def reload(module):
100+
"""Reload the module and return it.
101+
102+
The module must have been successfully imported before.
103+
104+
"""
105+
if not module or not isinstance(module, types.ModuleType):
106+
raise TypeError("reload() argument must be module")
107+
name = module.__name__
108+
if name not in sys.modules:
109+
msg = "module {} not in sys.modules"
110+
raise ImportError(msg.format(name), name=name)
111+
if name in _RELOADING:
112+
return _RELOADING[name]
113+
_RELOADING[name] = module
114+
try:
115+
parent_name = name.rpartition('.')[0]
116+
if parent_name and parent_name not in sys.modules:
117+
msg = "parent {!r} not in sys.modules"
118+
raise ImportError(msg.format(parentname), name=parent_name)
119+
return module.__loader__.load_module(name)
120+
finally:
121+
try:
122+
del _RELOADING[name]
123+
except KeyError:
124+
pass

Lib/test/test_importlib/test_api.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,18 @@ def test_nothing(self):
151151
self.assertIsNone(importlib.find_loader('nevergoingtofindthismodule'))
152152

153153

154+
class ReloadTests(unittest.TestCase):
155+
156+
"""Test module reloading for builtin and extension modules."""
157+
158+
def test_reload_modules(self):
159+
for mod in ('tokenize', 'time', 'marshal'):
160+
with self.subTest(module=mod):
161+
with support.CleanImport(mod):
162+
module = importlib.import_module(mod)
163+
importlib.reload(module)
164+
165+
154166
class InvalidateCacheTests(unittest.TestCase):
155167

156168
def test_method_called(self):

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ Core and Builtins
123123
Library
124124
-------
125125

126+
- Issue #18193: Add importlib.reload().
127+
126128
- Issue #18157: Stop using imp.load_module() in pydoc.
127129

128130
- Issue #16102: Make uuid._netbios_getnode() work again on Python 3.

0 commit comments

Comments
 (0)