When your script gets too long, it becomes a nightmare to maintain. In Python, every .py file is a Module. When you group these files into a folder, it becomes a Package (or a library).

Basic Import

Imagine you have a file named math_utils.py with some helper functions.

# math_utils.py
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

To use these in your main script (main.py), you just import them:

# main.py
import math_utils

# We use the 'dot' notation to access the functions
print(math_utils.add(5, 10))

Selective Imports (from ... import)

If you only need one specific tool from a file, don’t bring the whole toolbox. This keeps your code cleaner and saves memory.

# main.py
from math_utils import add

print(add(5, 10)) # No need for 'math_utils.' prefix now

Renaming with as

Sometimes a module has a long name, or it conflicts with a name you already used. You can give it a “nickname.”

# main.py
import math_utils as mu

print(mu.multiply(2, 5))

Packages (Folders)

When you have dozens of files, you put them in a folder. To Python, a folder with an __init__.py file (even if it’s empty) is a Package.

Project Structure:

my_project/
├── main.py
└── utilities/
    ├── __init__.py
    ├── strings.py
    └── numbers.py

To get something from the strings.py file inside the utilities folder:

from utilities.strings import clean_text

“Execution” Trap: if __name__ == "__main__":

This is the most confusing part for beginners. When you import a file, Python runs every line of code in that file.

If your math_utils.py has a print("Hello!") at the bottom, it will print that every time you import it into a new script. To prevent this, we use a “Guard”:

# math_utils.py
def add(a, b):
    return a + b

# This code ONLY runs if you run THIS file directly.
# It will NOT run if you import this file elsewhere.
if __name__ == "__main__":
    print("Testing the add function:")
    print(add(2, 2))

Internal vs. External Libraries

  • Internal (Standard Library): Modules that come with Python (e.g., import math, import os, import random).
  • External (Third-Party): Libraries other people wrote (e.g., requests, pandas, pydantic). You install these using a package manager like pip or uv.