Import Model

As we’ve seen, qualification is needed only when you use import to fetch a module as a whole. When you use the from statement, you copy names from the module to the importer, so the imported names are used without qualifying. Here are a few more details on the import process.

Imports Happen Only Once

One of the most common questions beginners seem to ask when using modules is: why won’t my imports keep working? The first import works fine, but later imports during an interactive session (or in a program) seem to have no effect. They’re not supposed to, and here’s why:

  • Modules are loaded and run on the first import or from.

  • Running a module’s code creates its top-level names.

  • Later import and from operations fetch an already loaded module.

Python loads, compiles, and runs code in a module file only on the first import, on purpose; since this is an expensive operation, Python does it just once per process by default. Moreover, since code in a module is usually executed once, you can use it to initialize variables. For example:

% cat simple.py
print 'hello'
spam = 1                   # initialize variable

% python
>>> import simple          # first import: loads and runs file's code
hello
>>> simple.spam            # assignment makes an attribute
1
>>> simple.spam = 2        # change attribute in module
>>>
>>> import simple          # just fetches already-loaded module
>>> simple.spam            # code wasn't rerun: attribute unchanged
2

In this example, the print and = statements run only the first time the module is imported. The second ...

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.