O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

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

Importing a Module

The difference between importing a module and running a script is that a module object is created in memory with a name you can access. All the functions and classes defined in the module go into the newly created namespace. When executing a script, all code is executed in the global namespace. You could let the user import modules by typing import foo in a console, or even in a script executed in this manner. However, there are some benefits to exposing this in the user interface. For example, you could save a list of standard imports for each user in the registry as a configuration variable and import those modules every time the application starts up. To do this, let’s take a look at Python’s import mechanism, which gives fine-grained control of how modules are created.

The library module imp exposes Python’s import mechanism. This includes functions to search the Python path for modules, and to load modules once located. Let’s say you create a simple module in the file c:\temp\import\temp.py that defines one function called func( x ). If you want to use this from PythonWin, ensure it’s on the path and type import temp. Within a custom application, you can often drop to a lower level of detail and customize the details of this process. For example, the text for a module might be a compiled resource in the program rather than a file on disk, and you might want to swap different source files in and out under the same module name. Let’s look at what happens ...

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