How to import the class within the same directory or sub directory?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
When working on a project in Python, properly organizing and accessing your classes by importing them effectively is crucial for maintainability and scalability of the code. Importing classes from the same directory or a subdirectory can seem straightforward, but it's important to understand the nuances to avoid common pitfalls such as module not found errors. This article explains how to import classes within the same directory or sub-directory, with technical explanations and examples provided.
Understanding Python Packages and Modules
Before diving into importing classes, it's essential to understand what packages and modules in Python are:
- Module: A module is a single Python file containing Python code including classes, functions, or variables.
- Package: A package is a directory that contains Python modules and a special
__init__.pyfile, which indicates to Python that this directory should be treated as a package.
Importing Classes from the Same Directory
When your script or application grows, you may find it useful to separate different parts of your code into multiple classes. If these classes are in the same directory, you can easily import them by using their module name. Here's how this works:
Assuming that we have two Python files in the same directory: main.py and helper.py. The helper.py file contains a class named HelperClass.
You can import HelperClass in main.py like so:
Importing Classes from a Subdirectory
To manage a larger codebase, organizing classes into subdirectories (making them packages) is common. Let's say we have a directory layout as follows:

