PYTHON IMPORTS
A beginner's guide to understanding and using Python import statements
WHAT ARE PYTHON IMPORTS?
Think of imports like checking out tools from a library. When you write Python code, you don't want to build everything from scratch - you want to use code that already exists (either Python's built-in tools or libraries other people wrote).
An import statement tells Python: "I need this specific tool, go find it and make it available for me to use."
WITHOUT IMPORTS
You would have to:
- ❌ Write your own HTTP request code from scratch
- ❌ Build your own data analysis functions
- ❌ Recreate math functions that already exist
- ❌ Reinvent the wheel for every project
WITH IMPORTS
You can:
-
✓
Use
import requestsfor HTTP calls -
✓
Use
import pandasfor data work -
✓
Use
import mathfor calculations - ✓ Stand on the shoulders of giants
THREE WAYS TO IMPORT
import pandas
df = pandas.DataFrame(data)
USE WHEN: You'll use multiple things from the module
BENEFIT: Crystal clear where each function comes from
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
USE WHEN: You only need one or two specific things
BENEFIT: Cleaner code, less typing
from math import * # DON'T DO THIS!
result = sqrt(16) # Where did sqrt come from?
WARNING: Imports EVERYTHING from the module
PROBLEM: Pollutes your namespace, causes naming conflicts, hard to debug
PRACTICAL GUIDELINES: WHICH STYLE TO USE?
import pandas as pd
import numpy as np
df = pd.DataFrame()
arr = np.array([1,2,3])
Standard conventions (pd, np) keep code readable
from datetime import datetime
from pathlib import Path
now = datetime.now()
p = Path("data.csv")
Clean when you only need one or two things
from os import *
# Now you have 100+ names
# Hard to know what's what!
Avoid unless in interactive shell
def process_data():
import pandas # Wrong!
# Imports belong at the top
Imports should be at the top of your file
COMMON IMPORT ERRORS AND WHAT THEY MEAN
Python can't find the module you're trying to import.
# Solution: Install it first!
pip install requests
The module exists, but doesn't have the thing you're trying to import.
# Check spelling and documentation
# Maybe you meant: pd.DataFrame not from pandas import DataFrame?
File A imports File B, File B imports File A. Python gets confused.
# Solution: Reorganize your code
# Move shared code to a third file
Never name your files the same as libraries! Python imports YOUR file instead.
# Don't: pandas.py, requests.py, flask.py
# Do: data_analysis.py, scraper.py, web_app.py
HOW PYTHON FINDS YOUR MODULES
When you type import something, Python searches in this order:
The folder where your script is running
Custom directories you've told Python to check
Where Python installed its built-in modules
Where pip installs external libraries
import sys
print(sys.path)
# Shows all directories Python searches
DEMYSTIFYING: if __name__ == "__main__"
This confuses EVERYONE at first. Here's what it means:
# my_script.py
print(__name__)
# Running: python my_script.py
# Output: __main__
Python sets __name__ to "__main__"
# other_file.py
import my_script
# my_script.py's __name__ is now:
# "my_script"
Python sets __name__ to the module name
# data_processor.py
def process_data():
return "Processed!"
if __name__ == "__main__":
# This ONLY runs when you execute this file directly
# NOT when someone imports it
print(process_data())
# Now you can BOTH:
# 1. Run it: python data_processor.py
# 2. Import it: from data_processor import process_data
Use this pattern to make your scripts reusable as modules!
QUICK REFERENCE: COMMON IMPORT PATTERNS
import pandas as pd
import numpy as np
df = pd.read_csv("data.csv")
arr = np.array([1,2,3])
import requests
from bs4 import BeautifulSoup
r = requests.get(url)
soup = BeautifulSoup(r.text)
from pathlib import Path
import json
p = Path("data/file.json")
data = json.load(p.open())
from datetime import datetime
import time
now = datetime.now()
time.sleep(1)
import re
pattern = r'\d+'
match = re.search(pattern, text)
from flask import Flask, request
app = Flask(__name__)
data = request.json
RELATIVE VS ABSOLUTE IMPORTS
ABSOLUTE IMPORTS
# project/utils/helpers.py
from project.data.loader import load_csv
# Full path from project root
BENEFIT: Clear, unambiguous
USE: Preferred in most cases
RELATIVE IMPORTS
# project/utils/helpers.py
from ..data.loader import load_csv
# .. = go up one directory
BENEFIT: Portable modules
WARNING: Can be confusing
WITHOUT PROPER IMPORTS
Going to EVERY hardware store in town to buy individual screws, ONE AT A TIME, every time you need them. You're recreating tools you already own because you can't find them.
WITH PROPER IMPORTS
Having a well-organized toolbox. You know exactly where each tool is, you grab what you need when you need it, and you can borrow tools from neighbors (libraries) when necessary.
GOLDEN RULES FOR IMPORTS
ALL IMPORTS AT THE TOP. Put them at the beginning of your file, not scattered throughout.
AVOID STAR IMPORTS. from x import * makes code hard to debug.
ONE IMPORT PER LINE. Makes it easier to read and track down issues.
GROUP YOUR IMPORTS. Standard library first, then third-party, then your own modules.
DON'T NAME FILES AFTER LIBRARIES. Never create pandas.py, requests.py, etc.
USE STANDARD ALIASES. import pandas as pd, import numpy as np - everyone knows these.
Master imports early. They're the foundation of every Python project.
When you understand imports, the entire Python ecosystem opens up to you.