Imports Happen Only Once

One of the most common questions people seem to ask when they start using modules is, “Why won’t my imports keep working?” They often report that the first import works fine, but later imports during an interactive session (or program run) seem to have no effect. In fact, they’re not supposed to. This section explains why.

Modules are loaded and run on the first import or from, and only the first. This is on purpose—because importing is an expensive operation, by default Python does it just once per file, per process. Later import operations simply fetch the already loaded module object.

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

As one consequence, because top-level code in a module file is usually executed only once, you can use it to initialize variables. Consider the file simple.py, for example:

print('hello')
spam = 1                   # Initialize variable

In this example, the print and = statements run the first time the module is imported, and the variable spam is initialized at import time:

% python
>>> import simple          # First import: loads and runs file's code
hello
>>> simple.spam            # Assignment makes an attribute
1

Second and later imports don’t rerun the module’s code; they just fetch the already created module object from Python’s internal modules table. Thus, the variable spam is not reinitialized:

>>> simple.spam = 2        # Change attribute in module
>>> import simple          # Just fetches already loaded module
>>> simple.spam            # Code wasn't rerun: attribute unchanged
2

Of course, sometimes you really want a module’s code to be rerun on a subsequent import. We’ll see how to do this with Python’s reload function later in this chapter.