{article Dive into Python}{title} {text} {readmore}{/article}

import module vs. from module import

The basic import statement (no from clause) is executed in two steps:

  1. find a module, loading and initializing it if necessary
  2. define a name or names in the local namespace for the scope where the import statement occurs

Python's from statement lets you import specific attributes from a module into the current namespace.

Examples:

import foo # foo imported and bound locally
import foo.bar.baz # foo.bar.baz imported, foo bound locally
import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
from foo.bar import baz # foo.bar.baz imported and bound as baz
from foo import attr # foo imported and foo.attr bound as attr


Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.


>>> import types
>>> types.FunctionType
<class 'function'>
>>> FunctionType
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
FunctionType
NameError: name 'FunctionType' is not defined
>>> from types import FunctionType
>>> FunctionType
<class 'function'>
>>>

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.

FunctionType by itself has not been defined in this namespace; it exists only in the context of types

This syntax imports the attribute FunctionType from the types module directly into the local namespace

Now FunctionType can be accessed directly, without reference to types.

When should you use from module import?

  1. If you will be accessing attributes and methods often and don't want to type the module name over and over,
  2. If you want to selectively import some attributes and methods but not others, use from module import.
  3. If the module contains attributes or functions with the same name as ones in your module, you must use import module to avoid name conflicts.