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 requests for HTTP calls
  • Use import pandas for data work
  • Use import math for calculations
  • Stand on the shoulders of giants

THREE WAYS TO IMPORT

STYLE 1: IMPORT ENTIRE MODULE
import pandas df = pandas.DataFrame(data)

USE WHEN: You'll use multiple things from the module

BENEFIT: Crystal clear where each function comes from

STYLE 2: IMPORT SPECIFIC ITEMS
from bs4 import BeautifulSoup soup = BeautifulSoup(html)

USE WHEN: You only need one or two specific things

BENEFIT: Cleaner code, less typing

STYLE 3: IMPORT EVERYTHING (DANGEROUS!)
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?

✓ GOOD: IMPORT ENTIRE MODULE
import pandas as pd import numpy as np df = pd.DataFrame() arr = np.array([1,2,3])

Standard conventions (pd, np) keep code readable

✓ GOOD: IMPORT SPECIFIC ITEMS
from datetime import datetime from pathlib import Path now = datetime.now() p = Path("data.csv")

Clean when you only need one or two things

❌ BAD: STAR IMPORTS
from os import * # Now you have 100+ names # Hard to know what's what!

Avoid unless in interactive shell

❌ BAD: IMPORTING IN FUNCTIONS
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

ModuleNotFoundError: No module named 'requests'

Python can't find the module you're trying to import.

# Solution: Install it first! pip install requests
ImportError: cannot import name 'DataFrame' from 'pandas'

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?
Circular Import Error

File A imports File B, File B imports File A. Python gets confused.

# Solution: Reorganize your code # Move shared code to a third file
You named your file pandas.py

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:

01
Current Directory

The folder where your script is running

02
PYTHONPATH Environment Variable

Custom directories you've told Python to check

03
Standard Library Locations

Where Python installed its built-in modules

04
Site-Packages (pip installed libraries)

Where pip installs external libraries

DEBUG TIP: SEE PYTHON'S SEARCH PATH
import sys print(sys.path) # Shows all directories Python searches

DEMYSTIFYING: if __name__ == "__main__"

This confuses EVERYONE at first. Here's what it means:

WHEN YOU RUN A FILE DIRECTLY
# my_script.py print(__name__) # Running: python my_script.py # Output: __main__

Python sets __name__ to "__main__"

WHEN YOU IMPORT A FILE
# other_file.py import my_script # my_script.py's __name__ is now: # "my_script"

Python sets __name__ to the module name

WHY IT MATTERS: REUSABLE CODE
# 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

Data Analysis
import pandas as pd import numpy as np df = pd.read_csv("data.csv") arr = np.array([1,2,3])
Web Scraping
import requests from bs4 import BeautifulSoup r = requests.get(url) soup = BeautifulSoup(r.text)
File Operations
from pathlib import Path import json p = Path("data/file.json") data = json.load(p.open())
Dates & Times
from datetime import datetime import time now = datetime.now() time.sleep(1)
Regular Expressions
import re pattern = r'\d+' match = re.search(pattern, text)
Web Framework
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

FOR BEGINNERS: Stick with absolute imports until you're comfortable with project structure.
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

01

ALL IMPORTS AT THE TOP. Put them at the beginning of your file, not scattered throughout.

02

AVOID STAR IMPORTS. from x import * makes code hard to debug.

03

ONE IMPORT PER LINE. Makes it easier to read and track down issues.

04

GROUP YOUR IMPORTS. Standard library first, then third-party, then your own modules.

05

DON'T NAME FILES AFTER LIBRARIES. Never create pandas.py, requests.py, etc.

06

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.