Modules, packages and imports

Every AI file starts with imports: import os, import json, from dotenv import load_dotenv. Modules let you organize code into files and install third-party libraries. Let us understand how Python finds and loads code.

Python import resolution

Where Python looks when you write import X

modules_and_packages.py
python
# Importing standard library modules
import os
import json
from pathlib import Path

# Use what you imported
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")

# from ... import (pick specific things)
from datetime import datetime
now = datetime.now()
print(f"Right now: {now.strftime('%Y-%m-%d %H:%M')}")

# Import with alias
# import pandas as pd    # standard alias
# import numpy as np     # standard alias

import gets the whole module. from...import picks specific items. Aliases like pd and np are conventions the Python community follows.

Python searches in order: 1) the current directory, 2) installed packages (pip/uv), 3) the standard library. This is why you can import your own files from the same folder, and why pip install makes libraries available everywhere.

When Python runs a file directly, it sets a special variable __name__ to "__main__". When the file is imported as a module, __name__ is set to the module name instead. This lets you write code that only runs when the file is executed directly, not when imported.

modules_and_packages.py
python
# Installing packages
# pip install python-dotenv   # traditional
# uv add python-dotenv        # modern (faster)
# uv sync                     # install all from pyproject.toml

# The __name__ guard: appears in EVERY course file
def main():
    print("Running as main script!")
    print("If imported, this will not run.")

if __name__ == "__main__":
    main()
    print(f"__name__ = {__name__}")  # __main__

The if __name__ == "__main__" guard runs code only when the file is executed directly, not when imported. uv is faster than pip and manages virtual environments automatically.

Quiz: Quiz

Loading practice…

Flashcards: Flashcards

Loading practice…

Validation checklist: Modules checklist

Loading practice…

Quiz: Quiz

Loading practice…