Skip to Content
Python in a Nutshell
book

Python in a Nutshell

by Alex Martelli
March 2003
Intermediate to advanced
656 pages
39h 30m
English
O'Reilly Media, Inc.
Content preview from Python in a Nutshell

Module Loading

Module-loading operations rely on attributes of the built-in sys module (covered in Chapter 8). The module-loading process described here is carried out by built-in function __import__. Your code can call __import__ directly, with the module name string as an argument. __import__ returns the module object or raises ImportError if the import fails.

To import a module named M, __import__ first checks dictionary sys.modules, using string M as the key. When key M is in the dictionary, __import__ returns the corresponding value as the requested module object. Otherwise, __import__ binds sys.modules[ M ] to a new empty module object with a __name__ of M, then looks for the right way to initialize (load) the module, as covered in Section 7.2.2 later in this section.

Thanks to this mechanism, the loading operation takes place only the first time a module is imported in a given run of the program. When a module is imported again, the module is not reloaded, since __import__ finds and returns the module’s entry in sys.modules. Thus, all imports of a module after the first one are extremely fast because they’re just dictionary lookups.

Built-in Modules

When a module is loaded, __import__ first checks whether the module is built-in. Built-in modules are listed in tuple sys.builtin_module_names, but rebinding that tuple does not affect module loading. A built-in module, like any other Python extension, is initialized by calling the module’s initialization function. The search ...

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

Python in a Nutshell, 3rd Edition

Python in a Nutshell, 3rd Edition

Alex Martelli, Anna Ravenscroft, Steve Holden
Python in a Nutshell, 4th Edition

Python in a Nutshell, 4th Edition

Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, Paul McGuire
Data Wrangling with Python

Data Wrangling with Python

Jacqueline Kazil, Katharine Jarmul

Publisher Resources

ISBN: 0596001886Supplemental ContentCatalog PageErrata