Python for AIPython 3.10+ · Pydantic 2.12
Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
34 small wins to finish your pathNext lesson →

import and modules

import is the statement that loads a module, a .py file or an installed package, so your code can use the functions inside it.

Last updated: 30 Sep, 2026 · Python 3.14

Python comes with a large standard library, and every package you install later, from Pydantic to a model SDK, is used the same way: import it, then call what is inside.

Syntax:

python
import module
from module import name

Importing a standard module

Example
import math

tokens = 1234
print(tokens / 1000)
print(math.ceil(tokens / 1000))

import math makes the math module available, and a dot reaches into it. math.ceil rounds up, which is how a price per started thousand is worked out.

Importing names directly

Example
from datetime import date, timedelta

ordered = date(2026, 3, 3)
expected = ordered + timedelta(days=5)
print(expected)
print(date(2026, 3, 10) > expected)

from datetime import date, timedelta brings those two names in, so you write date instead of datetime.date. A timedelta is a length of time, and adding it to a date gives a later date.

Importing your own module

Any .py file is a module. Move categorise from Functions into a file called triage.py:

Exampletriage.py
def categorise(text):
    text = text.lower()
    if "charged" in text or "refund" in text:
        return "billing"
    if "parcel" in text or "arrived" in text:
        return "shipping"
    return "other"
Example
from triage import categorise

print(categorise("Can I get a refund for the blue mug?"))

The file name without .py is the module name. The file must be in the same folder as the code importing it, which is the case here.

Importing a module that is not there

Example
import triage_tools

ModuleNotFoundError means Python looked and found no file or installed package with that name.

import module vs from module import name

import mathfrom math import ceil
You writemath.ceil(x)ceil(x)
Clear where it comes fromYesLess so in a long file
Brings inThe whole moduleOnly the names listed

Where imports show up in AI code

  • The first lines of every AI program: import json, from pydantic import BaseModel, a model SDK.
  • Splitting a project into files, such as tools in one module and the agent in another.
Watch out. Do not name your own file after a module you import. A file called json.py or math.py in your folder is found first, and the real module stops working.
Try it yourself
  • Print math.sqrt(144).
  • Add a function is_urgent(text) to triage.py and import both names with a single import statement.
  • Try import triage as t and call t.categorise.

Every expert started right here.