Lesson 10.2: Import Statements
What you will learn:
- How to use
import module_nameto import an entire module - How to use
from module import functionto import specific items - How to create aliases with
import module as alias - What actually happens when Python imports a module
1. The Basic import Statement
The simplest way to use a module is with the import keyword. This imports the entire module, and you access its contents using dot notation:
import math # Use dot notation: module_name.function_name result = math.sqrt(49) print(result) # 7.0 print(math.pi) # 3.141592653589793 print(math.ceil(4.3)) # 5
3.141592653589793
5
module.function() that tells Python to look inside a specific module for a function or variable. Think of it like saying "from the math module, use the sqrt function."
The advantage of this approach is that it is very clear where each function comes from. When you see math.sqrt(), you immediately know it is from the math module.
2. The from...import Statement
If you only need specific functions from a module, you can import just those functions. This lets you use them without the module name prefix:
Importing Specific Functions
# Import only what you need from math import sqrt, pi # Now use them directly - no "math." needed result = sqrt(64) print(result) # 8.0 print(pi) # 3.141592653589793 # But other math functions are NOT available: # print(ceil(4.3)) # NameError! ceil was not imported
3.141592653589793
Importing Multiple Items
from random import randint, choice, shuffle # All three functions are directly available print(randint(1, 10)) print(choice(["a", "b", "c"])) names = ["Alice", "Bob", "Charlie"] shuffle(names) print(names)
b
['Charlie', 'Alice', 'Bob']
from math import * which imports everything. This is generally discouraged because it can cause naming conflicts and makes it unclear where functions come from. Stick to importing specific items.
3. Creating Aliases with import...as
Sometimes module names are long. You can create a shorter alias (nickname) using as:
Module Aliases
# Create a shorter name for a module import datetime as dt now = dt.datetime.now() print(now.strftime("%Y-%m-%d")) # Common aliases you'll see in Python code: # import numpy as np (data science) # import pandas as pd (data analysis) # import matplotlib.pyplot as plt (plotting)
Function Aliases
# You can also alias specific imports from math import sqrt as square_root from random import randint as random_number result = square_root(36) print(result) # 6.0 num = random_number(1, 100) print(num)
42
4. Comparing Import Styles
Here is a side-by-side comparison of the three import styles:
Three Ways to Import
# Style 1: Import the whole module import math print(math.sqrt(16)) # Must use math.sqrt # Style 2: Import specific items from math import sqrt print(sqrt(16)) # Use sqrt directly # Style 3: Import with an alias import math as m print(m.sqrt(16)) # Use shorter alias
4.0
4.0
| Style | Best When | Consideration |
|---|---|---|
import math | Using many functions from a module | Very clear, but more typing |
from math import sqrt | Using only a few specific functions | Less typing, but less clear origin |
import math as m | Module name is long or has a convention | Good balance of clarity and brevity |
5. What Happens During Import
When Python encounters an import statement, several things happen behind the scenes:
- Python searches for the module in its list of known locations
- The module code runs once (Python executes the file)
- A module object is created that contains all the functions and variables
- The name is bound in your program so you can use it
import statement simply reuses the already-loaded module.
Import Order Convention
# Best practice: put all imports at the top of your file # Group them in this order: # 1. Standard library imports import math import random from datetime import datetime # 2. Third-party imports (installed with pip) # import requests # import pandas as pd # 3. Your own modules # from my_module import my_function # Your code starts here print("Program begins!")
Check Your Understanding
If you write from random import choice, can you later use random.randint(1, 10)?
No. When you use from random import choice, you only import the choice function, not the entire random module. To use randint, you would need to either add it to the import (from random import choice, randint) or import the whole module separately (import random).
Key Takeaways
import mathimports the entire module; usemath.sqrt()to access functionsfrom math import sqrtimports justsqrt; use it directly without the prefiximport math as mcreates an alias; usem.sqrt()- Avoid
from module import *as it can cause naming conflicts - Place all imports at the top of your file, grouped by type
- Python only executes a module's code once, even if imported multiple times