In this lesson, you will learn how to navigate your project’s file system by using absolute and relative paths to bring code from one module into another.
As your projects grow, you’ll eventually need to organize your files into sub-packages (directories containing an __init__.py file). To use code from these files, you need to tell Python exactly where to find them.
Absolute Imports
An absolute import specifies the path to a module starting from the root of your project. Think of this like a full GPS address; it tells Python exactly where to go regardless of where you are currently sitting in your project.
If you have a project structure like this:
my_project/
├── main.py
└── database/
├── connection.py
└── utils.py
From main.py, you would import a function from connection.py using the full package path:
from database.connection import connect_to_db
This is generally the preferred style because it is explicit and easy to read.
Relative Imports
Relative imports describe the location of a module in relation to the file you are currently working in. They use dots (.) to represent the directory structure. One dot (.) represents the current package, and two dots (..) represent the parent package.
If you are working inside database/utils.py and need to use a function from database/connection.py, you could use a relative import:
# Inside database/utils.py
from .connection import connect_to_db
This tells Python, "Look in my current directory for the connection module."
Choosing Between Them
Absolute imports are clearer and usually recommended for most situations. They stay the same even if you move your files around within the project. Relative imports, however, are useful when you are building a deeply nested package and don't want to type out the entire path from the project root every time. Just remember: relative imports only work if the code is being run as part of an installed or structured package.
Key Takeaway: Use absolute imports for clarity and consistency, and reserve relative imports for shortening paths within your internal package structure.