When you need an import
In the challenges on this site, all the classes of a program are usually in one file, main.py. A class can use any other class in the same file just by its name. You don't need an import for a class in the same file.
A common mistake is to copy an import line from an example where the classes were in separate files. Python then looks for a file that isn't there, and stops before it even gets to your classes:
from author import Author
class Author:
def __init__(self, name):
self.name = name
print(Author("Ana Lind").name)
Traceback (most recent call last):
File "main.py", line 1, in <module>
from author import Author
ModuleNotFoundError: No module named 'author'The fix is to delete the import line: the class Author is right there in the file.
Classes in a file of their own
As a program grows, its classes often move into files of their own. Each file is a module, just like the modules you wrote yourself in part 7, and a file that uses a class from another file has to import it. Here the class Product is in the file shop.py, and main.py imports it:
from shop import Product
cart = [Product("Tea", 3.5), Product("Bread", 2.25)]
for item in cart:
print(item)class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name}: {self.price}"Tea: 3.5
Bread: 2.25from shop import Product means: in the file shop.py, find the name Product. Without that line, main.py would stop with NameError: name 'Product' is not defined, because the class isn't in main.py.
Python's own modules
Classes from Python's standard library live in other files too, so they need an import as well. An object from the datetime module can be an attribute like any other object:
from datetime import date
class Loan:
def __init__(self, title, due):
self.title = title
self.due = due
def is_late(self, today):
return today > self.due
loan = Loan("World Atlas", date(2026, 3, 14))
print(loan.due)
print(loan.is_late(date(2026, 3, 10)))
print(loan.is_late(date(2026, 3, 20)))
2026-03-14
False
TrueSo the rule is short: you need an import for code that is in another file, either a module of Python's own or a file of yours. A class in the same file never needs one.