# Dive Into Python Python for experienced programmers | Find:

## 3.2. Importing modules using `from module import`

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

### Example 3.4. `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'>

| The `types` module contains no methods, just 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 only exists 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`?

- If you will be accessing attributes and methods often and don’t want to type the module name over and over, use `from module import`.
- If you want to selectively import some attributes and methods but not others, use `from module import`.
- 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.

Other than that, it’s just a matter of style, and you will see Python code written both ways.

### Further reading

- eff-bot has more to say on `import module` vs. `from module import`.
- Python Tutorial discusses advanced import techniques, including `from module import *`.