Module & Package Architecture
Published by Brayan K
Learn how to structure and scale large Python applications. Master the architectural patterns used by Django, FastAPI, Airflow, and enterprise teams to build maintainable codebases with thousands of files.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
How a big project's files import each other
Modules and Packages stopped at a dot, from . import prices, and at two modules that import each other. This lesson picks up there: what a package's __init__.py is for, __all__, relative imports, python -m, circular imports, code that runs at import, and how to lay out the folders. The layers and patterns a large application is organised into are in Architecture Patterns for Python Apps (MVC, Clean Architecture).
Every example writes its files first and only then imports them. A small write() function does it, with the mkdir(parents=True, exist_ok=True) and write_text() from Modern File Paths with pathlib, so it can make a package's folder as well.
__init__.py runs first, and it's the package's front door
The first time any part of a package is imported, its __init__.py runs, before the module you asked for:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", 'print("running shop/__init__.py")\n')
write("shop/prices.py", 'print("running shop/prices.py")\nVAT = 0.2\n')
import shop.prices
print(shop.prices.VAT)
# ✅ Expected output:
# running shop/__init__.py
# running shop/prices.py
# 0.2So __init__.py is the place to gather what callers should use. This one collects a function from each of two modules, and callers import both from the package without knowing which file holds which:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/prices.py", '''VAT = 0.2
def with_vat(amount):
return round(amount * (1 + VAT), 2)
''')
write("shop/receipts.py", '''from .prices import with_vat
def receipt(items):
total = sum(with_vat(price) for price in items.values())
return f"{len(items)} items, total {total:.2f}"
''')
write("shop/__init__.py", '''from .prices import with_vat
from .receipts import receipt
''')
from shop import receipt, with_vat
print(receipt({"tea": 3.5, "cake": 2.25}))
print(with_vat(10))
print(with_vat.__module__)
# ✅ Expected output:
# 2 items, total 6.90
# 12.0
# shop.priceswith_vat.__module__ names the module it really lives in. Move it to another file inside shop, change one line in __init__.py, and no caller notices. The standard library works the same way: json is a folder of modules, and its __init__.py hands out names from json/decoder.py:
import json
print(json.__all__)
print(json.JSONDecodeError.__module__)
print(json.JSONDecodeError is json.decoder.JSONDecodeError)
# ✅ Expected output:
# ['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder']
# json.decoder
# True__all__ decides what a star import copies, and nothing else
Modules and Packages advised against from module import *, which copies a module's names into yours. Without __all__, it copies every name that doesn't start with an underscore, including modules the file imported for its own use:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/prices.py", '''import math
VAT = 0.2
def with_vat(amount):
return _round_up(amount * (1 + VAT))
def _round_up(amount):
return math.ceil(amount * 100) / 100
''')
from shop.prices import *
print("VAT" in globals(), "with_vat" in globals())
print("_round_up" in globals(), "math" in globals())
# ✅ Expected output:
# True True
# False Trueglobals() is the dictionary of the program's own names. __all__, a list of names as strings at the top of a module, replaces that rule: a star import copies exactly those names. It hides nothing else, though, and every name can still be imported by name:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/prices.py", '''import math
__all__ = ["with_vat"]
VAT = 0.2
def with_vat(amount):
return _round_up(amount * (1 + VAT))
def _round_up(amount):
return math.ceil(amount * 100) / 100
''')
from shop.prices import *
print(with_vat(9.99))
print("VAT" in globals(), "_round_up" in globals(), "math" in globals())
from shop.prices import VAT, _round_up
print(VAT, _round_up(1.001))
# ✅ Expected output:
# 11.99
# False False False
# 0.2 1.01A leading underscore is how Python code says "internal", and nothing enforces it. A name in __all__ that doesn't exist goes unnoticed until a star import asks for it:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", '''__all__ = ["with_vat", "checkout"]
def with_vat(amount):
return round(amount * 1.2, 2)
''')
import shop
print(shop.with_vat(10))
from shop import *
# ✅ Expected output:
# 12.0
# ✅ Expected error:
# AttributeError: module 'shop' has no attribute 'checkout'A relative import counts from the package, not the folder
In a relative import, one dot means the package the module belongs to, and two dots the package above that. A module's __package__ holds that package's name:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/config.py", "RATE = 0.2\n")
write("shop/reports/__init__.py", "")
write("shop/reports/weekly.py", 'print(__name__, "is in package", __package__)\n')
write("shop/reports/daily.py", '''from ..config import RATE
from . import weekly
print(__name__, "is in package", __package__)
def line(amount):
return f"{amount} + VAT = {round(amount * (1 + RATE), 2)}"
''')
from shop.reports.daily import line
print(line(10))
# ✅ Expected output:
# shop.reports.weekly is in package shop.reports
# shop.reports.daily is in package shop.reports
# 10 + VAT = 12.0Two dots can't climb above the top package, even when the file you want is right there:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("config.py", "RATE = 0.2\n")
write("shop/__init__.py", "")
write("shop/report.py", "from ..config import RATE\n")
import shop.report
# ✅ Expected error:
# ImportError: attempted relative import beyond top-level packageOnly from can start with a dot: import .prices is SyntaxError: invalid syntax. And a habit from older code, a module importing its neighbour by its bare name, fails as soon as the module is imported as part of its package. This example catches the error and prints it:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/prices.py", "VAT = 0.2\n")
write("shop/report.py", "import prices\nprint(prices.VAT)\n")
try:
import shop.report
except ModuleNotFoundError as err:
print("ModuleNotFoundError:", err)
# ✅ Expected output:
# ModuleNotFoundError: No module named 'prices'A bare name is looked for on sys.path, which starts with the folder of the program you ran, not shop. Run as a program with python shop/report.py, the same file works, because shop/ is then the first folder searched, so the mistake hides until something imports the module. Write from . import prices, or from shop import prices.
python -m runs a module as part of its package
In a terminal, from the project folder, the one that holds shop/, these two commands differ:
python -m shop.report
python shop/report.pyThe first imports shop, then runs report.py as the program, as part of shop, so its relative imports work; it also puts the project folder first on sys.path. The second runs report.py as a plain file with no package, and puts shop/ first. There, a relative import stops with ImportError: attempted relative import with no known parent package, and from shop.prices import VAT with ModuleNotFoundError: No module named 'shop'. -m takes a module name, with dots: given shop/report.py, it fails and suggests shop/report, which fails too. And typed in another folder, python -m shop.report can't find shop at all.
The Run button has no terminal, but runpy.run_module() is what -m calls. Modules and Packages used its partner, runpy.run_path(), for python file.py:
import runpy
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/prices.py", '''VAT = 0.2
def with_vat(amount):
return round(amount * (1 + VAT), 2)
''')
write("shop/report.py", '''from .prices import with_vat
print("10 with VAT:", with_vat(10))
''')
runpy.run_module("shop.report", run_name="__main__")
runpy.run_path("shop/report.py", run_name="__main__")
# ✅ Expected output:
# 10 with VAT: 12.0
# ✅ Expected error:
# ImportError: attempted relative import with no known parent packageA whole package can be run too. python -m shop runs shop/__main__.py, as part of the package:
import runpy
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/prices.py", '''VAT = 0.2
def with_vat(amount):
return round(amount * (1 + VAT), 2)
''')
write("shop/__main__.py", '''from .prices import with_vat
print("running as", __name__, "in package", __package__)
print("10 with VAT:", with_vat(10))
''')
runpy.run_module("shop", run_name="__main__")
# ✅ Expected output:
# running as __main__ in package shop
# 10 with VAT: 12.0Without a __main__.py, run_module("shop") stops with ImportError: No module named shop.__main__; 'shop' is a package and cannot be directly executed, and in a terminal python -m shop prints the same words after the path of the Python it ran.
One more trap: the file you run is the module "__main__". If another module imports it by its file name, Python loads it a second time under that name, and its top-level code runs twice:
import runpy
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("main.py", '''print("running main.py as", __name__)
import helpers
TAX = 0.2
if __name__ == "__main__":
print(helpers.price_with_tax(10))
''')
write("helpers.py", '''import main
def price_with_tax(amount):
return round(amount * (1 + main.TAX), 2)
''')
runpy.run_path("main.py", run_name="__main__")
# ✅ Expected output:
# running main.py as __main__
# running main.py as main
# 12.0Keep shared values such as TAX in a module of their own, which both files import, and never import the file you run.
Why two modules that import each other can fail
sys.modules is Python's dictionary of every module loaded so far, by name. Python puts a module in it before running the module's code, not after:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("prices.py", '''import sys
print("while prices.py runs:", "prices" in sys.modules)
VAT = 0.2
''')
import sys
print("before the import:", "prices" in sys.modules)
import prices
print("after:", sys.modules["prices"] is prices)
# ✅ Expected output:
# before the import: False
# while prices.py runs: True
# after: TrueSo when orders.py imports customers.py, and customers.py imports orders while orders is still running, Python hands customers the half-run orders module from sys.modules rather than running it again. The prints show the order things happen in:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/orders.py", '''print("orders: start")
from . import customers
print("orders: end")
''')
write("shop/customers.py", '''print("customers: start")
from . import orders
print("customers: end")
''')
import shop.orders
print("program: done")
# ✅ Expected output:
# orders: start
# customers: start
# customers: end
# orders: end
# program: doneThat works, because neither file uses a name from the other until later. A from … import name needs the name at once, and here it doesn't exist yet. The message ends with the file's path, which is different on every computer. This example catches the error and removes that exact suffix using the exception's path attribute:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/orders.py", '''from .customers import find_customer
def place_order(name):
return "order for " + find_customer(name)
''')
write("shop/customers.py", '''from .orders import place_order
def find_customer(name):
return name.title()
''')
try:
import shop.orders
except ImportError as err:
print(str(err).removesuffix(f" ({err.path})"))
# ✅ Expected output:
# cannot import name 'place_order' from partially initialized module 'shop.orders' (most likely due to a circular import)Inside a package, every Python from 3.10 to 3.14 words it that way. For two modules next to the program, as in Modules and Packages, Python 3.13 and 3.14 say instead ImportError: cannot import name 'place_order' from 'orders' (consider renaming '…/orders.py' if it has the same name as a library you intended to import), without a word about a cycle.
Which file is imported first matters too. If orders.py does from .customers import find_customer and customers.py does from . import orders, then import shop.orders works and import shop.customers fails. A program can run fine while a test that imports customers first breaks.
Untangling a cycle
The best fix makes the imports point one way. Move what both modules need into a module that imports neither of them:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/names.py", '''def find_customer(name):
return name.title()
''')
write("shop/orders.py", '''from .names import find_customer
def place_order(name):
return "order for " + find_customer(name)
''')
write("shop/customers.py", '''from .names import find_customer
from .orders import place_order
def reorder(name):
return place_order(name) + " (again)"
''')
from shop.customers import reorder
print(reorder("alan turing"))
# ✅ Expected output:
# order for Alan Turing (again)A quicker fix imports inside the function that needs the name, which runs after both modules have loaded. It works, but it hides the cycle rather than removing it:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/orders.py", '''from .customers import find_customer
def place_order(name):
return "order for " + find_customer(name)
''')
write("shop/customers.py", '''def find_customer(name):
return name.title()
def reorder(name):
from .orders import place_order
return place_order(name) + " (again)"
''')
from shop.customers import reorder
print(reorder("alan turing"))
# ✅ Expected output:
# order for Alan Turing (again)Type hints cause many cycles: orders.py imports Customer only to write customer: Customer, while customers.py imports Order to make orders. Import the class only for the type checker, with TYPE_CHECKING:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/orders.py", '''from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .customers import Customer
class Order:
def __init__(self, customer: Customer, total: float) -> None:
self.customer = customer
self.total = total
''')
write("shop/customers.py", '''from .orders import Order
class Customer:
def __init__(self, name: str) -> None:
self.name = name
self.orders: list[Order] = []
def buy(self, total: float) -> Order:
order = Order(self, total)
self.orders.append(order)
return order
''')
from typing import TYPE_CHECKING
from shop.customers import Customer
ada = Customer("Ada")
order = ada.buy(12.5)
print(order.customer.name, order.total, len(ada.orders))
print(TYPE_CHECKING)
# ✅ Expected output:
# Ada 12.5 1
# FalseTYPE_CHECKING is False while the program runs and True for a type checker such as mypy, so the import happens only for mypy. The from __future__ import annotations line from Type Hints & Static Typing with mypy keeps Python from looking the hint up when it defines __init__. Without it, Python 3.10 to 3.13 stop with NameError: name 'Customer' is not defined; 3.14 no longer looks hints up at that point.
One more thing to keep in mind when modules share a setting: Modules and Packages showed that from binds a name to the same object the source name refers to at import time; it does not copy that object. Rebinding the source name later leaves this binding unchanged, while mutating a shared object is visible through both names. Read a replaceable setting through its module:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/config.py", "RATE = 0.2\n")
write("shop/prices.py", '''from .config import RATE
from . import config
def with_vat_copied(amount):
return round(amount * (1 + RATE), 2)
def with_vat_live(amount):
return round(amount * (1 + config.RATE), 2)
''')
import shop.config
from shop.prices import with_vat_copied, with_vat_live
shop.config.RATE = 0.25
print(with_vat_copied(10), with_vat_live(10))
# ✅ Expected output:
# 12.0 12.5Code at the top of a module runs when it's imported
Every top-level line in a module runs the first time it's imported, by the program and by every test that imports it. Work done there happens even when nothing needs it, and its errors happen at the import line:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("settings.py", '''from pathlib import Path
print("settings.py: reading rate.txt")
RATE = float(Path("rate.txt").read_text(encoding="utf-8"))
''')
print("program starts")
try:
import settings
except FileNotFoundError as err:
print("the import failed, missing", err.filename)
# ✅ Expected output:
# program starts
# settings.py: reading rate.txt
# the import failed, missing rate.txtMove the work into a function, and importing the module only defines it:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("settings.py", '''from pathlib import Path
def load_rate(path="rate.txt"):
return float(Path(path).read_text(encoding="utf-8"))
''')
write("rate.txt", "0.2")
import settings
print("imported; nothing read yet")
print(settings.load_rate())
# ✅ Expected output:
# imported; nothing read yet
# 0.2Sometimes the import-time work is the point. A registry like the @command one in Decorators & Advanced Features fills only when the module holding the decorated functions is imported:
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/commands.py", '''commands = {}
def command(func):
commands[func.__name__] = func
return func
''')
write("shop/plugins/__init__.py", "")
write("shop/plugins/greetings.py", '''from ..commands import command
@command
def hello():
return "Hello!"
''')
from shop.commands import commands
print(list(commands))
import shop.plugins.greetings
print(list(commands))
print(commands["hello"]())
# ✅ Expected output:
# []
# ['hello']
# Hello!importlib.import_module() imports a module whose name is in a string, for plugins listed in a settings file, say. Given package=, it takes a relative name too:
import importlib
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/commands.py", '''commands = {}
def command(func):
commands[func.__name__] = func
return func
''')
write("shop/plugins/__init__.py", "")
write("shop/plugins/greetings.py", '''from ..commands import command
@command
def hello():
return "Hello!"
''')
write("shop/plugins/farewells.py", '''from ..commands import command
@command
def bye():
return "Goodbye!"
''')
from shop.commands import commands
for name in ["greetings", "farewells"]:
module = importlib.import_module("shop.plugins." + name)
print("loaded", module.__name__)
print(sorted(commands))
print(importlib.import_module(".plugins.greetings", package="shop").__name__)
# ✅ Expected output:
# loaded shop.plugins.greetings
# loaded shop.plugins.farewells
# ['bye', 'hello']
# shop.plugins.greetingsLaying out a bigger project
A layout that puts this lesson together, with the package beside its tests:
shop-project/
main.py
shop/
__init__.py
__main__.py
config.py
prices.py
orders.py
customers.py
reports/
__init__.py
daily.py
tests/
test_prices.pyThe rules this lesson's examples back up:
- one front door per package, its __init__.py;
- relative imports inside the package, absolute ones from outside it;
- run it with python -m from the project folder;
- imports that point one way, with settings at the bottom;
- no work at import time, beyond defining things.
A src layout puts the package in src/shop/, next to pyproject.toml, so it can't be imported from the project folder by accident: there, python -m shop says No module named shop until the project is installed, which Packaging & Publishing Python Libraries to PyPI covers, or until the PYTHONPATH setting names src. Where tests go and how they import the package is in Testing with pytest: Fixtures, Parametrisation & Mocks.
Practice: untangle a cycle
As first written, orders.py did from .customers import find_customer, and importing customers stopped with ImportError: cannot import name 'find_customer' from partially initialized module 'shop.customers' (most likely due to a circular import), followed by the file's path. Change orders.py to import the module instead of the name, and use the name through the module inside the function. The two comments under the code give the answers, in order.
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("shop/__init__.py", "")
write("shop/customers.py", '''from .orders import place_order
def find_customer(name):
return name.title()
def reorder(name):
return place_order(name) + " (again)"
''')
write("shop/orders.py", '''from . ___ customers
def place_order(name):
return "order for " + customers.___(name)
''')
from shop.customers import reorder
print(reorder("alan turing"))
# 👉 replace ___ with import
# 👉 replace ___ with find_customer
# ✅ Expected output:
# order for Alan Turing (again)It works because from . import customers only needs the customers module, which sys.modules already holds, half-run, and find_customer is looked up later, when place_order() is called.
On your own: a quiz package
Write a package quiz. quiz/questions.py holds QUESTIONS, three (question, answer) pairs, with "4", "Paris" and "3" as the answers. quiz/scoring.py has score(answers), which imports QUESTIONS with a relative import and returns text like "2 of 3 right". quiz/__init__.py hands out QUESTIONS and score and lists them in __all__, and quiz/__main__.py prints a practice score. The program then does from quiz import *, prints the number of questions and the score for ["4", "Rome", "3"], and runs the package as python -m quiz would.
import runpy
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
# your code hereimport runpy
from pathlib import Path
def write(path, text):
file = Path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text, encoding="utf-8")
write("quiz/questions.py", '''QUESTIONS = [
("2 + 2", "4"),
("capital of France", "Paris"),
("10 // 3", "3"),
]
''')
write("quiz/scoring.py", '''from .questions import QUESTIONS
def score(answers):
right = 0
for (question, answer), given in zip(QUESTIONS, answers):
if given == answer:
right += 1
return f"{right} of {len(QUESTIONS)} right"
''')
write("quiz/__init__.py", '''from .questions import QUESTIONS
from .scoring import score
__all__ = ["QUESTIONS", "score"]
''')
write("quiz/__main__.py", '''from . import score
print("Practice run:", score(["4", "Paris", "3"]))
''')
from quiz import *
print(len(QUESTIONS), "questions")
print(score(["4", "Rome", "3"]))
runpy.run_module("quiz", run_name="__main__")
# ✅ Expected output:
# 3 questions
# 2 of 3 right
# Practice run: 3 of 3 right__main__.py takes score from the package's front door, from . import score, so it keeps working if score moves to another module inside quiz.
Practice quiz
shop/__init__.py prints A, and shop/prices.py prints B and sets VAT = 0.2. A program runs import shop.prices, then import shop, then print(shop.prices.VAT). What does it print?
- B, A, 0.2
- A, B, A, 0.2
- A, B, 0.2
- B, 0.2
Answer: A, B, 0.2. Importing shop.prices runs the package's __init__.py first, then prices.py. The second import finds shop in sys.modules and runs nothing.
shop/prices.py has __all__ = ["with_vat"], VAT = 0.2 and with_vat(). After from shop.prices import *, the program runs print(with_vat(10)) and then print(VAT). What happens?
- It prints 12.0, then 0.2
- It prints 12.0, then stops with NameError: name 'VAT' is not defined
- It stops with ImportError at the star import
- It stops with AttributeError: module 'shop.prices' has no attribute 'VAT'
Answer: It prints 12.0, then stops with NameError: name 'VAT' is not defined. The star import copies only the names in __all__. VAT is still there in the module, and from shop.prices import VAT would get it.
config.py sits next to the program, and shop/report.py starts with from ..config import RATE. What does import shop.report do?
- It stops with ImportError: attempted relative import beyond top-level package
- It works, and shop.report.RATE is the RATE from config.py
- It stops with ModuleNotFoundError: No module named 'config'
- It stops with ImportError: attempted relative import with no known parent package
Answer: It stops with ImportError: attempted relative import beyond top-level package. shop is the top package, so two dots would go above it. The program's own folder isn't a package.
shop/report.py starts with from .prices import VAT. Which command, typed in a terminal, runs it without an error?
- python shop/report.py, from the project folder
- python report.py, from inside shop
- python -m shop.report, from the project folder
- python -m shop/report.py, from the project folder
Answer: python -m shop.report, from the project folder. -m imports report.py as part of shop, so the dot has a package to count from. Run by its path, report.py is a plain program with no package, and -m wants a module name with dots, not a path.
In package shop, orders.py starts with from .customers import find_customer, and customers.py starts with from . import orders. Which of these, as the program's first import, stops with an ImportError?
- import shop.orders
- Both of them
- Neither of them
- import shop.customers
Answer: import shop.customers. Starting from customers, orders runs while customers is half-run and asks it for find_customer, which isn't defined yet. Starting from orders, customers only needs the orders module itself, which sys.modules already holds.
shop/prices.py does from .config import RATE and uses RATE in with_vat(). The program imports shop.config and with_vat, sets shop.config.RATE = 0.5, and prints with_vat(10). RATE started as 0.2. What does it print?
- 15.0
- 12.0
- It stops with AttributeError
- 10.0
Answer: 12.0. The from-import bound prices.RATE to the original float. Rebinding config.RATE does not rebind prices.RATE; no object was copied.
main.py prints "start" and then imports helpers; helpers.py does import main. What does running main.py as the program print?
- start, once
- It stops with ImportError: circular import
- Nothing
- start, twice
Answer: start, twice. The program runs as the module __main__. import main finds no module called main, so Python runs main.py a second time under that name.
shop/report.py starts with import prices, meaning shop/prices.py. What does a program in the project folder get from import shop.report?
- ModuleNotFoundError: No module named 'prices'
- It works, and shop.report.prices is shop.prices
- ImportError: attempted relative import with no known parent package
- ImportError: cannot import name 'prices'
Answer: ModuleNotFoundError: No module named 'prices'. A bare name is looked for on sys.path, which holds the project folder, not shop/. Write from . import prices.
Continue this course
- Previous: Design Patterns in Python (Singleton, Factory, Strategy)
- Next: Logging, Debugging & Error Handling at Scale — Add structured logging, use pdb, and handle errors in production
- Quick reference: Python cheat sheet › Environment & Tooling
Frequently asked questions
Does mypy warn about circular imports?
No. For a package whose orders.py and customers.py import each other's classes for their hints, mypy 1.19.1 reports Success: no issues found in 4 source files, while the program stops with the partially initialized ImportError. Type checking and running the imports are different jobs; Type Hints & Static Typing with mypy shows how to run mypy.
Why does this site's editor sometimes say No module named … for a file my program has just written?
The Run button's Python remembers what a folder held when it last imported from it, so a module written after an import from the same folder can be missed. Write every file before the first import, as this lesson's examples do, or call importlib.invalidate_caches() before importing, which makes Python look at the folders again.
What does "found in sys.modules after import of package" mean?
Python's RuntimeWarning: 'shop.report' found in sys.modules after import of package 'shop', but prior to execution of 'shop.report'; this may result in unpredictable behaviour. It appears when shop/__init__.py imports report and you then run python -m shop.report: report.py runs twice, once as shop.report and once as the program. Don't import, in __init__.py, a module you also run with -m.
Which standard-library modules can I run with -m?
Several. python -m json.tool data.json prints a JSON file indented, on Python 3.10 to 3.14, and from 3.14 python -m json does the same. Earlier versions say No module named json.__main__; 'json' is a package and cannot be directly executed. python -m pip is from Modules and Packages.
How do I import my project's modules from a script in a subfolder?
Make the subfolder a package and run the script with python -m from the project folder, or install the project, which Packaging & Publishing Python Libraries to PyPI covers. Adding folders to sys.path in the script tends to make one file importable under two names, and then it runs twice.