O'Reilly logo

Python in a Nutshell by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required