Reloading Modules

At the start of the last section, we noted that a module’s code is run only once per process by default. To force a module’s code to be reloaded and rerun, you need to ask Python explicitly to do so, by calling the reload built-in function. In this section, we’ll explore how to use reload to make your systems more dynamic. In a nutshell:

  • Imports load and run a module’s code only the first time.

  • Later imports use the already loaded module object without rerunning code.

  • The reload function forces an already loaded module’s code to be reloaded and rerun.

Why all the fuss about reloading modules? The reload function allows parts of programs to be changed without stopping the whole program. With reload, the effects of changes in components can be observed immediately. Reloading doesn’t help in every situation, but where it does, it makes for a much shorter development cycle. For instance, imagine a database program that must connect to a server on startup; since program changes can be tested immediately after reloads, you need to connect only once while debugging.[37]

General Form

Unlike import and from :

  • reload is a built-in function in Python, not a statement.

  • reload is passed an existing module object, not a name.

Because reload expects an object, a module must have been previously imported successfully before you can reload it. (In fact, if the import was unsuccessful due to a syntax or other error, you may need to repeat an import before you can reload). Reloading ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.