Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata