5.2. from module import を使ってのインポート

Python にはモジュールをインポートする方法が 2 つあります. 両方とも有用であり, それらの使い分けを知らなくてはなりません. 1 つの方法は, Section 2.4, “全てはオブジェクト” で既に見た import module です. もう 1 つの方法でも同じ結果は得ますが, わずかですが重要な違いがあります.

以下が基本的な from module import 構文です.


from UserDict import UserDict

これはあなたが愛して止まない import module 構文に似ていますが, 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.

Note
from module import * in Python is like use module in Perl; import module in Python is like require module in Perl.
Note
from module import * in Python is like import module.* in Java; import module in Python is like import module in Java.

Example 5.2. import module vs. from module import

>>> import types
>>> types.FunctionType             1
<type 'function'>
>>> FunctionType                   2
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
NameError: There is no variable named 'FunctionType'
>>> from types import FunctionType 3
>>> FunctionType                   4
<type 'function'>
1 The types module contains no methods; it just has attributes for each Python object type. Note that the attribute, FunctionType, must be qualified by the module name, types.
2 FunctionType by itself has not been defined in this namespace; it exists only in the context of types.
3 This syntax imports the attribute FunctionType from the types module directly into the local namespace.
4 Now FunctionType can be accessed directly, without reference to types.

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.

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

Further Reading on Module Importing Techniques