liveBook · Manning

Import statement

As explained in Practices of the Python Pro

An import statement is a source-code declaration that makes names or definitions from another module, package, or namespace available in the current scope.

An import statement brings a name from another module into the namespace of the current module. This lets you split unrelated code into focused modules while making each dependency visible. section 2.1.1 section 2.3

Choose an import form according to how much functionality you need and how clearly its origin should remain visible:

  • Import one name directly: `from sales_tax import add_sales_tax`. Call it without a module prefix. section 2.1.2
  • Import a module as a whole: `import sales_tax`. Call its functions with a prefix such as `sales_tax.add_sales_tax()`. section 2.1.2
  • Alias a name with `as` when two imports would collide, such as `from mycoollibrary import datetime as cooldatetime`. section 2.1.3
  • Prefer explicit imports over `from module import *`; wildcard imports hide dependencies and make collisions harder to debug. section 2.1.2

Keeping similar names clear

Two modules can provide a name such as `time`. Importing both directly means the later definition replaces the earlier one. Qualified imports preserve the distinction: `import time`, `import datetime`, then `time.time()` and `datetime.time()`. section 2.1.3

# receipt.py

from sales_tax import add_sales_tax                     #1


def print_receipt():
    total = ...
    state = ...
    print(f'TOTAL: {total}')
    print(f'AFTER TAX: {add_sales_tax(total, state)}')  #2

A short receipt module shows a direct import connecting code in `receipt.py` to a function in `sales_tax.py`. section 2.1.1

As an application grows, packages organize related modules into directories. Imports then express that hierarchy, for example `import database.query` or `from database import query`; aliases can disambiguate similarly named modules. section 2.2.4

How Practices of the Python Pro covers it

How deep it goes
Explains direct, whole-module, aliased, wildcard, and package imports, stopping short of import execution internals.
Examples
Demonstrates sales-tax modules, receipt code, conflicting time names, aliases, and database and search packages.
What it assumes
Builds from Python modules, global namespaces, local namespaces, and names defined by functions, classes, and variables.
What you can do after
Apply it via Python import syntax to reuse module definitions, qualify names, avoid collisions, and structure packages.
How it connects
Connects imports to namespaces, modules, packages, name collisions, and separation of concerns.

Also explained in

Compare how 13 books explain import statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.