Split the Program into Modules
A program that lives in one file gets harder to read with every function you add. Python lets you split it into several files and use the functions of one file from another. This page explains how that works: what a module is, what happens when you import one, how to decide which function goes in which file, and how to write a short note on a function that says what types of values it takes and gives back.
Every Python file is a module
You have already imported modules that come with Python, such as json or pathlib. A module is simply a file of Python code that another file can use. The ones in the standard library were written by other people, but nothing about them is special: every .py file you write is a module too. Its module name is the file name without .py, so a file called greetings.py is the module greetings.
Say greetings.py holds one function. Another file in the same folder can use it by importing it. Python looks for the module first in the folder of the file you run, so two files side by side are all it takes: nothing has to be installed.
def greet(name):
return f"Hello, {name}!"from greetings import greet
print(greet("Ada"))The line from greetings import greet reads as: find the module greetings, take the name greet out of it, and make that name available in this file. After it, main.py calls greet as if the function had been written there. Running uv run main.py prints Hello, Ada!.
Two ways to write the import
There are two common forms, and they put different names into the importing file.
| You write | Name it adds to your file | How you call the function |
|---|---|---|
| from greetings import greet | greet | greet("Ada") |
| import greetings | greetings | greetings.greet("Ada") |
With from ... import you get the function by its own name, and the module name itself is not defined in your file. With a plain import greetings you get only the module name, and you reach the function with a dot, the same dot you use for a method. To take several functions at once, separate them with commas: from greetings import greet, wave. Imports go at the top of the file, so a reader sees at once which other files this one depends on.
Two mistakes stop an import. If Python finds no file with the module name, it raises ModuleNotFoundError. If the file exists but defines no function with the name you asked for (often a typo), it raises ImportError.
True or false?
After `from greetings import greet`, the file can also call `greetings.greet("Ada")`.
False. The `from` form adds only the name `greet`. The name `greetings` is not defined, so `greetings.greet` fails with a `NameError`.
A file in the same folder as the file you run can be imported without installing anything.
True. Python searches the folder of the file being run first, so a module sitting next to it is found.
Naming a module file
Because the file name becomes a name in your code, it has to follow the same rules as a variable name: letters, digits and underscores, not starting with a digit. A file called shopping-list.py runs fine with uv run, but no other file can import it, since import shopping-list reads as a subtraction. Python's style guide asks for short, all-lowercase module names, with underscores where they help reading: shopping_list.py.
Avoid names that the standard library already uses. The folder of the file you run is searched before the standard library, so a file of your own called json.py or random.py hides the real module. Every import json in the program then gets your file, and a function the real module has, such as json.loads, is suddenly missing. Recent Python versions point this out in the error message and suggest renaming the file.
What happens when a file is imported
An import does not pick functions out of a file. To make the module, Python runs the whole file, from the first line to the last, exactly as it would if you ran that file yourself. Every line at the top level, meaning not indented inside a function, is carried out.
A def line is one of those statements, but running it does not run the function. It only creates the function and gives it its name, ready to be called. The body inside the def runs later, each time something calls the function. Any other top-level line, such as a print, really runs during the import. This module has a print above and below its function:
print("greetings: start")
def greet(name):
return f"Hello, {name}!"
print("greetings: end")from greetings import greet
print(greet("Ada"))
print(greet("Sam"))True or false?
Running `main.py` prints `Hello, Ada!` first, because the import only fetches the function `greet`.
False. The import runs all of `greetings.py` before the next line of `main.py`, so its two `print` lines come first.
$ uv run main.py
greetings: start
greetings: end
Hello, Ada!
Hello, Sam!Follow the order. The first line of main.py is the import, so Python pauses main.py and runs greetings.py from top to bottom: it prints greetings: start, creates greet, prints greetings: end. Then it returns to main.py and carries on with the two calls. Each call runs the body of greet.
Only once per run
Python remembers every module it has already loaded during a run. When a second file imports greetings later in the same run, Python hands over the module it already has and does not run the file again, so greetings: start is printed once however many files import it. The memory lasts until the program ends; the next uv run starts fresh and runs the file again, with any changes you saved.
To make loading faster, Python also keeps a translated copy of each imported module in a folder called __pycache__ next to your files. It creates and updates that folder by itself; it is not part of your code, and you never edit it.
True or false?
If two different files of one program both import the same module, its top-level `print` appears once.
True. A module runs only the first time it is imported in a run. Later imports reuse the module Python already loaded.
Importing a module calls every function defined in it.
False. Running a `def` only creates the function. Its body runs when some code calls it.
Modules hold definitions, one file holds the steps
Since importing runs every top-level line, a module that prints, asks for input or loops at the top level does all of that the moment another file imports it. That is rarely what you want: you imported it to use its functions. So a module meant to be imported holds definitions (functions, and values that never change) and nothing that acts on its own.
The actions belong in one file: the file you run to start the program, often called main.py. It imports what it needs and then holds the steps: call this, then that, then print the result. Reading that one file tells you what the program does, and each module tells you how one part of it is done.
You will often see the starting file put its steps inside a function called main, with two lines at the bottom that call it:
from greetings import greet
def main():
print(greet("Ada"))
if __name__ == "__main__":
main()Those two lines rely on a variable Python creates in every module by itself, called __name__. Its value depends on how the file was reached:
- In a file that was imported, it holds the module name, such as
'greetings'. - In the file you started with
uv run, it holds the string'__main__'.
So the if at the bottom calls main() when you run the file, and does nothing when another file imports it, for example a file that only wants to check one of its functions. A file works without this if; it is a habit that keeps the steps from running by accident.
One job per module
Once a program can be split, the question is where to cut. A good rule is to group functions by what they are about. Picture a small to-do program. Some functions work on tasks: making one, marking one as done, counting the open ones. Others deal with the file the tasks are kept in: loading it and saving it. Those are two different jobs, so they go in two modules, and the starting file uses both.
- main.py the stepsThe starting file
Imports from both modules and calls their functions in order. It is the file you run.
- tasks.py new_task, mark_done, count_openAbout tasks
Functions that make and change tasks. None of them opens a file.
- storage.py load_tasks, save_tasksAbout the saved file
Functions that read and write the file the tasks are kept in. It imports
jsonandpathlibfrom the standard library. - json standard library
- pathlib standard library
- main.py to tasks.py: imports
- main.py to storage.py: imports
- storage.py to json: imports
- storage.py to pathlib: imports
Each arrow means "imports from". The split pays off in three ways:
- Reading. A question about saving sends you to
storage.pyand nowhere else. Each file is short enough to read in one go. - Changing. If you decide to save the tasks in a different format, only
storage.pychanges. As long asload_tasksandsave_taskskeep their names and what they take and give back,main.pydoes not notice. - Checking. You can import
tasks.pyon its own and trycount_openwith a few made-up tasks, without touching any file on disk or running the whole program.
A sign that a function is in the wrong module: it needs something the rest of that module never uses, such as a function about tasks that opens a file. Move it to the module whose job it shares.
True or false?
Changing how `storage.py` saves the tasks forces a change in every file that imports it.
False. Other files only use the function names and what they take and return. If those stay the same, the inside of the module can change freely.
Grouping functions by topic lets you try one module's functions without running the rest of the program.
True. A module of definitions can be imported on its own, and importing it runs nothing but its definitions.
Type hints: a note on what goes in and comes out
When functions live in another file, you can no longer see at a glance what they expect. Does count_open take one task or a list of them? Does it give back a number or print one? Python lets you write the answer on the function itself. A note attached to a parameter or a return value is called an annotation, and an annotation that names a type is called a type hint.
def total_minutes(hours: int, minutes: int) -> int:
return hours * 60 + minutesA colon after a parameter name, followed by a type, is the hint for that parameter: hours: int says hours is meant to be a whole number. An arrow -> between the closing bracket and the final colon gives the type of the return value. The line reads: total_minutes takes two whole numbers and gives back a whole number. With a default value, the hint comes first and spaces go around the equals sign: def repeat(text: str, times: int = 2) -> str:.
A few hints cover most functions:
| Hint | Means |
|---|---|
| int, float, str, bool | a whole number, a decimal number, a string, True or False |
| list[str] | a list whose items are strings |
| dict[str, int] | a dictionary with string keys and whole-number values |
| -> None | the function gives nothing back (it returns None) |
def count_long(words: list[str], limit: int) -> int:
count = 0
for word in words:
if len(word) > limit:
count = count + 1
return count
def show_task(title: str) -> None:
print(f"- {title}")The first function says it takes a list of strings and a whole number, and gives back a whole number. The second only prints, so its return type is None. The square brackets work on the built-in list and dict directly; nothing needs to be imported for them.
Python does not check them
A type hint is a note, not a rule. When the program runs, Python reads past it and never compares the argument with the hint. A call with the wrong type behaves exactly as it would without the hint:
def double(n: int) -> int:
return n * 2
print(double("ha"))$ uv run double.py
hahaThe hint says int, the call passes a string, and the program still runs: "ha" * 2 repeats the string. If the wrong type makes a line inside the function fail, the error you see comes from that line, not from the hint.
So who reads them? Three kinds of readers. Editors use them to show what a function expects while you type a call, and many of them mark a call that passes the wrong type. Type checkers are separate tools you run on your code; they read every hint and report mismatches like double("ha") before the program ever runs. And some libraries read the hints of your functions while the program runs and use them to decide what to do. A fourth reader matters too: a person opening the module months later, who learns from the first line of each function what it takes and what it gives back.
Hints are optional, and a function without them is still correct Python. They help most exactly where this page started: on the functions one file imports from another, where the caller cannot see the code.
True or false?
With the hint `n: int`, calling `double("ha")` stops the program with a type error.
False. Python does not enforce hints when the program runs. The call runs and returns `"haha"`; only an editor or a type checker would flag it.
In `def show_task(title: str) -> None:`, the `-> None` says the function gives nothing back.
True. The arrow names the type of the return value, and `None` is what a function returns when it has no `return` with a value.