How do I unload (reload) a Python module?

How do I unload (reload) a Python module?

You can reload a module when it has already been imported by using importlib.reload():

from importlib import reload  # Python 3.4+
import foo

while True:
    # Do some things.
    if is_changed(foo):
        foo = reload(foo)

In Python 2, reload was a builtin. In Python 3, it was moved to the imp module. In 3.4, imp was deprecated in favor of importlib. When targeting 3 or later, either reference the appropriate module when calling reload or import it.

I think that this is what you want. Web servers like Djangos development server use this so that you can see the effects of your code changes without restarting the server process itself.

To quote from the docs:

  • Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the loader which originally loaded the module. 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.

As you noted in your question, youll have to reconstruct Foo objects if the Foo class resides in the foo module.

In Python 3.0–3.3 you would use: imp.reload(module)

The BDFL has answered this question.

However, imp was deprecated in 3.4, in favour of importlib (thanks @Stefan!).

I think, therefore, you’d now use importlib.reload(module), although I’m not sure.

How do I unload (reload) a Python module?

It can be especially difficult to delete a module if it is not pure Python.

Here is some information from: How do I really delete an imported module?

You can use sys.getrefcount() to find out the actual number of

>>> import sys, empty, os
>>> sys.getrefcount(sys)
>>> sys.getrefcount(os)
>>> sys.getrefcount(empty)

Numbers greater than 3 indicate that
it will be hard to get rid of the
module. The homegrown empty
(containing nothing) module should be
garbage collected after

>>> del sys.modules[empty]
>>> del empty

as the third reference is an artifact
of the getrefcount() function.

Leave a Reply

Your email address will not be published. Required fields are marked *