预计阅读本页时间:-
Reloading Modules
As we’ve seen, 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 to do so explicitly by calling the reload built-in function. In this section, we’ll explore how to use reloads to make your systems more dynamic. In a nutshell:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
- Imports (via both import and from statements) load and run a module’s code only the first time the module is imported in a process.
- Later imports use the already loaded module object without reloading or rerunning the file’s code.
- The reload function forces an already loaded module’s code to be reloaded and rerun. Assignments in the file’s new code change the existing module object in-place.
Why all the fuss about reloading modules? The reload function allows parts of a program to be changed without stopping the whole program. With reload, therefore, 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; because program changes or customizations can be tested immediately after reloads, you need to connect only once while debugging. Long-running servers can update themselves this way, too.
Because Python is interpreted (more or less), it already gets rid of the compile/link steps you need to go through to get a C program to run: modules are loaded dynamically when imported by a running program. Reloading offers a further performance advantage by allowing you to also change parts of running programs without stopping. Note that reload currently only works on modules written in Python; compiled extension modules coded in a language such as C can be dynamically loaded at runtime, too, but they can’t be reloaded.
Note
Version skew note: In Python 2.6, reload is available as a built-in function. In Python 3.0, it has been moved to the imp standard library module—it’s known as imp.reload in 3.0. This simply means that an extra import or from statement is required to load this tool (in 3.0 only). Readers using 2.6 can ignore these imports in this book’s examples, or use them anyhow—2.6 also has a reload in its imp module to ease migration to 3.0. Reloading works the same regardless of its packaging.