Home > Dive Into Python > The Power Of Introspection > Importing modules using from module import | << >> |
diveintopython.org | |
Python for experienced programmers | |
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 chapter 1. The other way accomplishes the same thing but works in subtlely and importantly different ways.
Example 2.4. Basic from module import syntax
from types import BuiltinFunctionType, BuiltinMethodType, \ FunctionType, MethodType, ClassType
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.
Example 2.5. import module vs. from module import
>>> 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.
« The Power Of Introspection | Optional and named arguments » |