You are here: Home > Dive Into Python > Objects and Object-Orientation > Importing Modules Using from module import | << >> | ||||
Dive Into PythonPython from novice to pro |
Python has two ways of importing modules. Both are useful, and you should know when to use each. One way, import module, you've already seen in Section 2.4, “Everything Is an Object”. The other way accomplishes the same thing, but it has subtle and important differences.
Here is the basic from module import syntax:
from UserDict import UserDict
This is similar to the import module syntax that you know and love, but with an important difference: the attributes and methods of the imported module types are imported directly into the local namespace, so they are available directly, without qualification by module name. You can import individual items or use from module import * to import everything.
from module import * in Python is like use module in Perl; import module in Python is like require module in Perl. |
from module import * in Python is like import module.* in Java; import module in Python is like import module in Java. |
>>> import types >>> types.FunctionType <type 'function'> >>> FunctionType Traceback (innermost last): File "<interactive input>", line 1, in ? NameError: There is no variable named 'FunctionType' >>> from types import FunctionType >>> FunctionType <type 'function'>
When should you use from module import?
Other than that, it's just a matter of style, and you will see Python code written both ways.
Use from module import * sparingly, because it makes it difficult to determine where a particular function or attribute came from, and that makes debugging and refactoring more difficult. |
<< Objects and Object-Orientation |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
Defining Classes >> |