Relative imports in Python let you import a module using a path relative to the current module’s location, using dots (.) to refer to the current package and (..) to move up one level. They are the cleanest way to import between modules inside the same package, and they avoid the confusion of long absolute paths that can break when you rename a top-level package.
What Are Relative Imports?
In Python, an import statement normally uses an absolute module name, like import os or from mypackage import utils. A relative import instead uses leading dots to indicate how many levels up to go from the current module’s package. For example, if you are inside mypackage/subpackage/module.py, then:
from . import siblingimportsmypackage.subpackage.sibling(same directory).from .sibling import funcimportsfuncfrom that sibling module.from .. import parent_moduleimportsmypackage.parent_module(one level up).from ..utils import helperimportshelperfrommypackage.utils.
The number of dots is key: one dot means the current package, two dots mean the parent of the current package, and so on. You cannot go above the top-level package; that would raise an ImportError.
Why Use Relative Imports?
Relative imports keep your code self-contained and portable. If you rename the top-level package (say from myapp to my_application), you don’t have to update every internal import. They also make it obvious that a module belongs to the same package, improving readability. For example, inside a package pkg/, using from . import config is clearer than from pkg import config because it signals “this is a sibling module.”
They are especially useful in large projects with deep nesting. Instead of writing from myproject.services.database import connection everywhere, you can write from ..database import connection from a module in myproject/services/.
How Relative Imports Work (The Mechanics)
Python determines a module’s package by its __package__ attribute. When you run a script directly (e.g., python mypackage/module.py), __package__ is None or empty, and relative imports fail with ImportError: attempted relative import with no known parent package. That’s because the script’s directory is added to sys.path, not the package root.
To use relative imports, you must run your code as a module with the -m flag from the directory that contains the top-level package. For example, from the project root (the folder containing mypackage/), run:
python -m mypackage.module
This sets __package__ to 'mypackage' and allows from . import sibling to resolve correctly. Alternatively, you can install the package in editable mode (pip install -e .) and then run scripts from anywhere, because the package is properly registered.
Relative Imports vs. Absolute Imports
Absolute imports use the full path from the project root, like from mypackage.subpackage import module. They are unambiguous and work even when you run a script directly, as long as the project root is on sys.path. Relative imports are shorter and more resilient to package renames, but they require the module to be part of a package.
PEP 8 recommends absolute imports for clarity, but allows relative imports for intra-package references. In practice, many projects use relative imports for internal modules and absolute imports for external libraries. The choice often comes down to team preference and project structure.
Common Problems and Solutions
- “Attempted relative import with no known parent package” – This happens when you run a file directly. Solution: run with
python -m package.moduleor restructure your code so the file is always imported as a module. - Relative imports in scripts – If you have a script that needs to import a sibling module, you can’t use relative imports when running it directly. Instead, move the script into the package and run it with
-m, or use absolute imports after adding the parent directory tosys.path(though that’s a hack). - Circular imports – If module A imports from module B and B imports from A, you can get an
ImportErroreven with relative imports. Solution: move the shared code into a third module, or import inside functions/methods to defer the import. - Running in interactive shell – The interactive shell has no package context, so relative imports fail. You must use absolute imports or run a script file.
Relative Imports in Python 2 vs. Python 3
In Python 2, relative imports were implicit: import sibling would first look in the current package. This caused confusion and name clashes. Python 3 made all imports absolute by default, so import sibling only looks in sys.path. To use relative imports in Python 3, you must explicitly use the dot syntax. This is a breaking change, but it eliminates ambiguity. If you maintain legacy Python 2 code, be aware that from . import sibling is the explicit form that works in both, while plain import sibling behaves differently.
Best Practices and Tips
- Use relative imports for modules that are tightly coupled and will always live in the same package.
- Avoid going more than two levels up (e.g.,
from ... import) because it often indicates poor package design. - When in doubt, use absolute imports – they are more explicit and work in more contexts.
- If you have a mix of scripts and packages, keep scripts outside the package and have them import the package via absolute imports.
- Use
python -mfor any module that uses relative imports, and document this in your project’s README.
Frequently Asked Questions
Why do I get “attempted relative import with no known parent package”?
This error occurs when you run a Python file directly (like python mypackage/module.py) instead of as a module. When run directly, Python doesn’t know the package context, so the relative import has no parent package to resolve against. Run it with python -m mypackage.module from the directory above mypackage to fix it.
Can I use relative imports in a script that I run directly?
No, not if the script is the entry point. Relative imports require the module to be part of a package. If you run a script directly, you can only use absolute imports. To use relative imports, either make the script a module (run with -m) or move the logic into a package and have a thin wrapper script that imports it.
What does a single dot mean in an import?
A single dot (.) refers to the current package. For example, from . import utils imports the utils module from the same package as the current module. Two dots (..) refer to the parent package, and three dots (...) refer to the grandparent, and so on.
Are relative imports slower than absolute imports?
No, performance is essentially identical. The import system resolves the module name either way; the relative path is just a shorthand. The only overhead is a tiny bit of string manipulation, which is negligible compared to the actual module loading.
Should I use relative or absolute imports in my project?
It depends. For internal imports within a package, relative imports are concise and resilient to package renames. For imports from outside the package, you must use absolute imports. Many projects use a mix: relative for siblings, absolute for external dependencies. If you’re unsure, start with absolute imports – they are more explicit and work in more scenarios.
Related
- How to Select All Files in a Windows Folder (4 Ways)
- Multiple Imports on One Line? Python Style Guide
- Google Sheets Conditional Formatting Formula Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Set Out of Office in Outlook on Edge: Step-by-StepTo set an out-of-office reply in Outlook using Microsoft Edge, open Outlook on the web, select the Settings…
- Insert a Blank Row in Excel After Every Row of DataTo insert a blank row after every data row in Excel, add a temporary helper column, number your…
- Reaction Time Test Traffic Light: How It WorksA reaction time test traffic light is a simple online or app-based tool that measures how quickly you…
- Excel Power Query: Merge 3 TablesTo merge three tables in Excel Power Query, you perform two sequential merge operations: first merge two tables,…
- How to Center an Excel Table in Word Without Distorting ItTo center a copied Excel range in Word, click inside the table, choose Table Layout > Properties, open…
- Vendor Quote Comparison Template: Build It in ExcelYes. In Excel for Microsoft 365, create one row per vendor and columns for the quoted unit price,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.