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

Get Python in a Nutshell 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.