You can import attributes from a module into the local namespace directly by using one of the following lines of code:
• To import a specific item directly, type from, the module name, import, and the item name, as shown:
• from mymodule import myfunction
• To import all of a module's functions directly, type from, the module name, import, and an asterisk (*), a wildcard character that stands for "all." For example:
Warning! Most of the time it's a Bad Idea to use the import * syntax because
• You can't control what you're importing.
• You risk polluting the local namespace with all the names from the imported modules, which makes debugging much more difficult.
When you access module attributes through the module name, you're less likely to run into conflicts between the names inside one module and the names inside another module. And your code will be easier to read.
For example, you might have two modules that each have a function to combine two values in some way. If each module's function were named combine(), then if you tried to access each of these functions directly, you might accidentally use the wrong one, or readers of your code might not know which function you were using at any particular time. But if you always use modulename.combine(), then which function you're using is clear.
There's one situation, however, when it's appropriate to import an item from a module directly. That's when a module is a wrapper around a single class or function. For example, the module cstringio contains a single function called stringio(). (See Chapter 19 for details.) The simplest way to use stringio() is to import it with this line of code:
from cStringlO import StringlO
Tip If you don't remember the names of the functions inside a module, use the dir() command in interactive mode to list them, like this:
Was this article helpful?