Update for Python3: (quoted from the already-answered answer, since the last edit/comment here suggested a deprecated method)
In Python 3,
reload
was moved to theimp
module. In 3.4,imp
was deprecated in favor ofimportlib
, andreload
was added to the latter. When targeting 3 or later, either reference the appropriate module when callingreload
or import it.
Takeaway:
- Python3 >= 3.4:
importlib.reload(packagename)
- Python3 < 3.4:
imp.reload(packagename)
- Python2: continue below
Use the reload
builtin function:
https://docs.python.org/2/library/functions.html#reload
When
reload(module)
is executed:
- Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.
- As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.
- The names in the module namespace are updated to point to any new or changed objects.
- Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.
Example:
# Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py
# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py
# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2