← Back to Python Course | Chapter 8: Modules & Packages | Lesson 2 of 6

Python import Statement

Basic Import Statement

'import module_name' loads the whole module and requires you to prefix everything you use from it with the module name, like math.sqrt(16) -- this keeps your code's origin of each function clear even in files with many imports.

Example: Basic Import Statement

python
import math
print(math.sqrt(16))

Import Specific Items with 'from'

'from module import name' pulls a specific function, class, or variable directly into your file's namespace, so you can call sqrt(16) without the math. prefix -- convenient, but it's easier to lose track of where a name came from as a file grows.

Example: Import Specific Items with 'from'

python
from math import sqrt
print(sqrt(16))

Renaming Imports using 'as'

'import numpy as np' gives a module (or an imported name) a shorter local alias, which is why the ecosystem convention 'import numpy as np' and 'import pandas as pd' exists -- it saves keystrokes across a file that uses the library constantly.

Example: Renaming Imports using 'as'

python
import math as m
print(m.pi)

Wildcard Imports

'from module import *' pulls every public name from a module directly into your namespace at once, but doing this makes it hard to tell which function came from where and risks silently overwriting names you already defined -- most style guides recommend avoiding it.

Example: Wildcard Imports

python
from math import *
print(sqrt(25))  # unclear which module sqrt came from

Conditional and Dynamic Imports

Because import is a regular statement, you can put it inside a function, an if block, or a try/except -- this is used for optional dependencies (falling back gracefully if a library isn't installed) or to avoid an import's cost until that code path actually runs.

Example: Conditional and Dynamic Imports

python
try:
    import ujson as json_lib
except ImportError:
    import json as json_lib

print(json_lib.dumps({"a": 1}))
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.