g↗genai/ learner
Python for AI / Lesson 10

Modules and packages

A module is code you can import into your own file. Importing lets you use functions that are already written, such as the one that reads the JSON text an AI model sends back.

Concept + interactive labBeginner friendly

Modules and packages: Using code that is already written.

So far you have written each function yourself. Most programs also use functions that someone else has already written and tested.

Think of a workshop. A function is one tool. A module is a toolbox that holds tools. A package is a cabinet that holds toolboxes.

You will meet these terms in order:

  1. Module: code you can import. It is typically one file, and it holds functions.
  2. import: the line that makes a module's code usable in your file, under a name.
  3. Dot: tags.label means "the label inside tags".
  4. Package: a kind of module that can contain other modules. It is commonly a folder of files.
  5. Standard library: the modules and packages that come with Python.
  6. JSON: a text format for data. Many AI tools send their replies in it.
  7. json.loads: a ready-made function that turns JSON text into a Python value, such as a dict.
Running example (toy data)

A help desk sorts messages by topic. The file names, the function and the reply text are invented for this lesson.

Each code example is a fresh file: no names exist in it until its own lines create them.

A module is code you can import, typically one file.

You know how to write a function. Save it in a file, and other files can import that file as a module. Here is a file named tags.py:

# tags.py
def label(topic):
    return "Topic: " + topic

The module's name is the file name without .py, so this module is called tags. It holds one function, label.

An open toolbox with the name plate tags and the caption module. Inside it lies one spanner tagged label, with the caption function. The picture shows that a module holds a function.
The module tags holds the function label, the way a toolbox holds a tool.

A second file in the same folder, main.py, can now use that function without containing it:

# main.py (same folder as tags.py)
import tags
print(tags.label("refund"))

# Output when you run main.py:
# Topic: refund

Everyday example: a shared recipe card. You write the recipe once, and anyone in the kitchen can follow it without writing it out again.

A simplification: most modules you will meet are .py files. Some of Python's own modules are built differently, but you import them in the same way.

import creates one name in your file.

When Python runs import tags in main.py, it finds tags.py, runs it, and creates one name in main.py: tags.

A toolbox with the name plate tags on the left. One arrow labelled import points from it to a page headed main.py on the right. On the page sits a name tag that reads tags. The toolbox stays where it is.
import tags makes the module usable in main.py under the name tags. The module file itself is not moved or changed.

To use something inside the module, write the module name, a dot, then the function name: tags.label("refund").

Why a common mistake happens. This fresh file imports the module but calls the function without the module name:

import tags
print(label("refund"))

# NameError: name 'label' is not defined

The import line created only the name tags. No name label exists in this file, so Python stops with a NameError. The function is still inside the module, and tags.label reaches it.

Everyday example: the toolbox is on your desk, but the spanner is still inside it. You say which box first, then which tool.

Three import styles, three different names.

Python has three common ways to write an import. In a fresh file, each line below creates one name, and that name decides how you write the call.

  • import tags
    Name created
    tags
    The call
    tags.label("refund")
  • from tags import label
    Name created
    label
    The call
    label("refund")
  • import tags as t
    Name created
    t
    The call
    t.label("refund")

All three calls return "Topic: refund". The function is the same one. Only the name you reach it by changes.

  • from tags import label makes one function from the module usable by its own name. It does not create the name tags.
  • import tags as t gives the module a short nickname. It creates t, and it does not create tags.

Which one should you use? import tags shows most clearly where a function comes from. The as style is common for long module names.

Everyday example: saving a phone contact. You can save the full name, save only the one number you need, or save it under a nickname. You can then only dial by what you saved.

✎ Try it yourselfKnowledge check · Practice only

Practice: Which name exists?

A fresh file sits in the same folder as tags.py. In tags.py, the function label returns "Topic: " plus its argument. The fresh file has these two lines: from tags import label print(tags.label("refund")) What happens when you run the fresh file?

A package is a module that holds other modules.

When a project grows, related modules are grouped together. A package is a kind of module that can contain other modules. Commonly it is a folder of .py files.

Suppose the help desk moves its modules into a folder named helpdesk:

main.py
helpdesk/          <- a package (here, a folder)
    tags.py        <- a module (here, a file)
    replies.py     <- another module
An open cabinet with the name plate helpdesk and the caption package. Inside it stand two toolboxes with the name plates tags and replies; the tags toolbox has the caption module. The picture shows that a package holds modules.
The package helpdesk holds the modules tags and replies, the way a cabinet holds toolboxes.

The dot now also leads from the package to a module inside it. Both of these fresh versions of main.py print Topic: refund:

# Version 1
import helpdesk.tags
print(helpdesk.tags.label("refund"))

# Version 2
from helpdesk import tags
print(tags.label("refund"))

Real packages usually also have a file named __init__.py in the folder. This small example runs without one, and this lesson does not cover that file.

Everyday example: a folder on your computer named Holiday that holds several photo files. You find a photo by naming the folder first, then the file.

A note on the word: people also say "package" for something you install, such as pandas. Installing is not covered in this lesson.

Quick questions

Which holds which?
A package holds modules. A module holds functions. In this example, helpdesk holds tags, and tags holds label.
After import helpdesk.tags, how do you call label?
With the full dotted name: helpdesk.tags.label("refund").
Is a package also a module?
Yes. Python treats a package as a kind of module, one that can contain other modules.

The standard library comes with Python.

You do not have to write every module yourself. Python is shipped with a large set of modules and packages called the standard library.

That is why import json works in a fresh file, although you never wrote a file named json.py. A few standard library modules:

  • json: reads and writes JSON text.
  • math: mathematical functions.
  • random: random choices and numbers.
  • datetime: dates and times.

The standard library has packages too. urllib is one: it holds modules such as urllib.parse and urllib.request.

You import them with the same three styles you used for tags.

Everyday example: the apps that are already on a new phone. Other apps have to be installed first, and the same is true for packages such as pandas.

json.loads turns a JSON object into a dict.

JSON is a text format for data. Programs use it to send data to each other, and AI tools often reply in it.

A JSON object is JSON text in curly braces that pairs names with values. It looks like a Python dict, but it is text. In Python you hold it in a str:

reply = '{"topic": "refund", "urgent": true}'

Why a common mistake happens. Because reply looks like a dict, it is tempting to read a value from it straight away:

reply = '{"topic": "refund", "urgent": true}'
print(reply["topic"])

# TypeError: string indices must be integers, not 'str'

reply is a str, so Python sees only a row of characters. The function loads in the json module reads that text and builds a Python value from it:

import json
reply = '{"topic": "refund", "urgent": true}'
data = json.loads(reply)

print(data["topic"])   # refund
print(data)            # {'topic': 'refund', 'urgent': True}
print(type(reply))     # <class 'str'>
print(type(data))      # <class 'dict'>
A paper strip captioned JSON text on the left. An arrow leads into a machine labelled json.loads, and a second arrow leads out to an organiser tray captioned dict with two compartments tabbed topic and urgent.
In this example, the JSON text goes into json.loads and a dict with the keys topic and urgent comes out. The text in reply stays as it was.
  • data is a dict, so data["topic"] works as in the dictionaries lesson.
  • JSON writes true. In the dict it became Python's True.
  • A JSON object gives a dict. Other JSON gives other types: a JSON array, written in square brackets, gives a Python list.

One way to remember the name: loads is "load" plus "s", with the s for string.

Everyday example: a shopping list sent as a photo. You can see the items, but you cannot tick one off until someone types the list into your notes app.

json.loads needs valid JSON text. What to do when the text is not valid is the topic of the next lesson.

Quick questions

After data = json.loads(reply), is reply a dict now?
No. reply is still the same str. The dict is in data.
Where does the json module come from?
From the standard library, which comes with Python.
In json.loads, which part is the module and which is the function?
json is the module. loads is a function inside it.

Try the import bench.

Build a four-line program from two choices: an import line and a call. Each combination is a fresh file that holds only those four lines. The bench shows which name the import line created and whether the call can run.

Try it in this order:

  1. Start with No import line and the call json.loads(reply). Read the error.
  2. Choose import json. The same call now runs.
  3. Keep import json and choose the call loads(reply). Read which name is missing.
  4. Choose from json import loads, then find the one call that runs.
  5. Choose import json as j, then find the one call that runs.

Toy simulator: it applies one rule, "the call works only if its first name was created by the import line". It is not a live Python interpreter, and the reply text is invented.

1. Import line
Name created by the import linenone
2. Call
# (no import line)
reply = '{"topic": "refund", "urgent": true}'
data = json.loads(reply)
print(data["topic"])
ErrorNameError: name 'json' is not defined

There is no import line, so it created no name. The call starts with json, which was not created, so Python stops with a NameError.

Newer Python versions may add a hint after the error message, such as a suggestion to import json. The bench shows only the first part.

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

A fresh file has these three lines: import json reply = '{"topic": "refund", "urgent": true}' data = json.loads(reply) Which fourth line prints only refund?
THE TAKEAWAY

Take this with you.

  • Module and package: a module is typically one file that holds functions. A package is a kind of module that holds other modules, commonly a folder.
  • import creates a name: import json creates json, from json import loads creates loads, and import json as j creates j.
  • The dot reaches inside: json.loads means the loads function inside the json module.
  • JSON text is a str: use json.loads(reply) to get a dict from a JSON object, then read values with data["topic"].
Back to Chapter P1 →