Import Python Modules
Learn how to import and use Python modules effectively with a step-by-step tutorial, including core concepts, hands-on exercise, troubleshooting, and next steps.
Focus: import and use python modules
Ever written a Python script and found yourself typing the same math, date, or file operations over and over? You’re not alone. The secret weapon every Python developer reaches for is the module — a reusable, pre-built toolbox that saves you from reinventing the wheel. In this lesson, you’ll learn the simple yet powerful syntax to import and use Python modules, transforming your code from repetitive to elegant in just a few keystrokes.
The problem this lesson solves
Without modules, every Python script is an island. Need to calculate a square root? You’d write the algorithm from scratch. Working with JSON? You’d implement a parser yourself. This approach is not only tedious but error-prone — libraries that ship with Python (the standard library) have been tested by thousands of developers over decades. By not using them, you’re writing slower, less reliable code. The problem is that beginners often don’t know how to bring those tools into their own scripts, or they mix up the various import styles. This lesson solves that gap: you’ll learn the exact syntax to import modules and use their functions, classes, and constants with confidence.
Core concept / mental model
Think of Python itself as a giant workshop. Modules are like toolboxes sitting on the shelves. You don’t want to dump every tool onto your workbench at once — that’s chaos. Instead, you grab only the toolbox you need and open it. Importing a module is simply reaching for that toolbox and saying, “I’d like to use what’s inside.”
- A module is a file ending in
.pythat contains definitions (functions, classes, constants) and statements. - The
importstatement loads that file into memory and makes its contents available under a namespace (usually the module’s name). - Python’s standard library ships with hundreds of modules, and you can also write your own or install third-party ones.
Pro tip: A Python package is a directory containing multiple modules, but for now we focus on single-file modules.
Key definitions
- Namespace: The dotted prefix (like
math.) that groups a module’s members and prevents name collisions. import module— loads the module; you must usemodule.function().from module import something— loads onlysomethinginto your current namespace; you can call it without the prefix.import module as alias— gives the module a shorter nickname.
How it works step by step
When Python encounters an import statement, it follows a strict search order:
- Check
sys.modules— a cache of already-imported modules. If found, Python uses the cached object (import is fast and idempotent). - Search in
sys.path— a list of directories that includes: - The directory of the current script. - Directories in thePYTHONPATHenvironment variable. - Default site-packages for third-party libraries. - Standard library paths. - Find and load the module — Python reads the
.pyfile (or compiled.pyc) and executes its code, creating a module object. - Bind the name — the module object is assigned to the name you gave (e.g.,
math,json, or your custom alias).
The three import styles
| Style | Syntax | How to use | When to use |
|---|---|---|---|
| Direct | import math |
math.sqrt(16) |
Best for major libraries — keeps namespacing clean |
| Selective | from math import sqrt |
sqrt(16) |
Use when you only need a few items; avoids prefix noise |
| Alias | import numpy as np |
np.array([1,2,3]) |
Perfect for long module names; standard convention for pandas, numpy, etc. |
Step-by-step sequence
To demonstrate, here’s what happens when you run:
import math
result = math.sqrt(16)
print(result) # Output: 4.0
- Python looks up
sys.modules– nomathfound yet. - It scans
sys.pathand locatesmath.pyin the standard library directory. - It executes
math.py, creating a module object with functions likesqrt,sin,pi. - The name
mathin your script now refers to that module object. - Calling
math.sqrt(16)walks the namespace chain: findmath, then findsqrtinside, call it with16.
Hands-on walkthrough
Let’s practice with three real-world modules from the standard library: math, json, and datetime. Run these examples in your environment (or a Python REPL) as you read.
Example 1: Using math for calculations
import math
# Module attributes
print(f"Pi is approximately {math.pi:.2f}")
print(f"The square root of 25 is {math.sqrt(25)}")
print(f"The sine of 90 degrees is {math.sin(math.radians(90))}")
Expected output:
Pi is approximately 3.14
The square root of 25 is 5.0
The sine of 90 degrees is 1.0
Example 2: Selective import from json
from json import dumps, loads
# Convert a Python dict to JSON string
data = {"name": "Alice", "score": 42, "active": True}
json_string = dumps(data)
print(json_string) # '{"name": "Alice", "score": 42, "active": true}'
# Parse JSON back to dict
parsed = loads(json_string)
print(parsed["name"]) # Alice
Expected output:
{"name": "Alice", "score": 42, "active": true}
Alice
Example 3: Aliasing a long module name
datetime is a common module. We can alias it for brevity:
import datetime as dt
now = dt.datetime.now()
print(f"Current date and time: {now}")
print(f"Formatted: {now.strftime('%Y-%m-%d %H:%M:%S')}")
Expected output (example):
Current date and time: 2025-04-07 14:30:00.123456
Formatted: 2025-04-07 14:30:00
Example 4: Creating and importing your own module
Save this as my_tools.py in the same folder as your main script:
# my_tools.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
Then use it in main.py:
# main.py
import my_tools
msg = my_tools.greet("Dan")
print(msg) # Hello, Dan!
print(my_tools.PI) # 3.14159
Expected output:
Hello, Dan!
3.14159
Pro tip: If
main.pyandmy_tools.pyare in different directories, add the directory tosys.pathor restructure as a package. For now, keep them in the same folder.
Compare options / when to choose what
Here’s a quick-reference table to help you decide which import style fits your scenario:
| Scenario | Recommended style | Why |
|---|---|---|
| You need many functions from one library | import library |
Keeps namespace clear; avoids name clashes |
| You only need 1–2 specific functions | from library import func |
Less typing; no prefix clutter |
| The module has a conventional short alias | import pandas as pd |
Follows community standards; readable |
| You’re writing a small script in a silo | Either works | Use what feels more readable |
| You want to avoid inadvertently overriding built-ins | import library |
Safer; the prefix prevents shadowing |
When to avoid from module import *
Using the asterisk pulls all names from a module into your namespace. This is considered bad practice because: - It pollutes your namespace (you might accidentally overwrite your own variables). - It makes it unclear where a function came from. - It can silently shadow built-in functions.
# Avoid this:
from math import *
print(sqrt(9)) # Works, but where did 'sqrt' come from?
Better:
# Prefer this:
import math
print(math.sqrt(9))
Troubleshooting & edge cases
Error: ModuleNotFoundError: No module named 'requests'
This means the module you’re trying to import isn’t installed. Third-party packages need to be installed first via pip:
pip install requests
Then import normally:
import requests
response = requests.get('https://api.example.com')
Error: AttributeError: module 'math' has no attribute 'sqr'
You misspelled the function name. Double-check the correct spelling (it’s sqrt, not sqr). Use dir(module) to see all available attributes:
import math
print(dir(math))
Problem: Circular imports
If module A imports module B, and module B imports module A (directly or indirectly), Python may raise an ImportError. Solution: restructure your code — often by moving the shared logic into a third module, or importing inside a function to break the cycle.
# module_a.py
import module_b # OK
def func_a():
from module_b import func_b # Late import avoids circular issue
return func_b()
Edge case: Importing a module twice is free
Python caches modules after the first import. Re-importing simply returns the cached object:
import math
import math # No effect; same module object
This is safe and efficient.
Common mistake: Shadows built-in names
Never name your own file math.py or json.py — Python will find your file first, breaking standard library imports. Always use unique names for your modules.
What you learned & what's next
You’ve just mastered the art of importing and using Python modules. You understand:
- The mental model of modules as toolboxes with namespaces.
- Three import styles: direct (import math), selective (from math import sqrt), and alias (import datetime as dt).
- How to create and import your own .py files.
- Common pitfalls like misspelled names, module-not-found errors, and circular imports.
You can now confidently reuse Python’s standard library and third-party packages in your projects. This skill unlocks immediate productivity — no more reinventing basic utilities.
What’s next? In the next lesson, you’ll learn how to structure your own code across multiple files using Python packages — directories of modules that work together. Get ready to organize your growing codebase like a pro.
Practice recap
Mini exercise: Create a script that imports random and statistics. Generate a list of 10 random integers between 1 and 100, then use statistics.mean() to compute the average. Print both the list and the average. This will reinforce both importing multiple modules and using their functions together.
Common mistakes
- Forgetting to install third-party packages with
pipbefore importing them (e.g.,ModuleNotFoundError: No module named 'requests'). Always install first. - Using
from module import *which pollutes your namespace and makes source tracking difficult. Prefer explicit imports. - Shadowing built-in modules by naming your own file
math.py,json.py, etc. Python will find your file before the standard library, causing confusing errors. - Misspelling module functions (e.g.,
math.sqrinstead ofmath.sqrt). Usedir(module)to list all available names.
Variations
- Use
importlib.import_module('module_name')for dynamic imports where the module name is a string variable. - Use lazy imports (importing inside a function or class) to reduce startup time in large applications, especially for heavy modules like
matplotlib. - Use relative imports (
from . import sibling_module) inside packages to refer to sibling modules without hardcoding paths.
Real-world use cases
- A data analyst imports
pandasandnumpyto load, clean, and analyze CSV datasets in a Jupyter notebook. - A web developer uses
jsonto parse API responses anddatetimeto handle timestamps in a Django REST API. - A DevOps engineer imports
osandsubprocessto run system commands and manage environment variables in deployment scripts.
Key takeaways
- Modules are reusable
.pyfiles that bundle functions, classes, and constants — Python’s standard library is your best friend. - Use
import modulefor full namespace safety,from module import namewhen you only need a few items, andimport module as aliasfor long names. - Python caches imported modules in
sys.modules— re-importing is instant and safe. - Avoid
from module import *— it pollutes your namespace and obscures source of names. - Creating your own module is as simple as writing a
.pyfile and importing it from another script in the same folder. - Import errors usually stem from missing packages, misspelled names, or circular imports — use
pip,dir(), and refactoring to debug.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.