Programming
Class Import
Directory Management
Coding Tips
Python Tutorial

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__.py file, 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.

python
1# In helper.py
2class HelperClass:
3    def display_message(self):
4        print("Hello from HelperClass")

You can import HelperClass in main.py like so:

python
1# In main.py
2from helper import HelperClass
3
4helper_instance = HelperClass()
5helper_instance.display_message()

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:

 
1project_directory/
2| --------------------- | ----------------------------------------------------------------- |
3| Module | A single Python file (.py) containing definitions and statements. |
4| Package | A directory with `__init__.py` file and multiple modules. |
5| Import Same Directory | `from module_name import ClassName` |
6| Import Subdirectory | `from package.module_name import ClassName` |
7| Best practice | Use absolute imports and maintain a clear directory structure. |
8
9By understanding and applying these conventions and tips for imports in Python, you can structure your code more efficiently and reduce errors significantly, leading to a more robust and maintainable codebase.

Course illustration
Course illustration

All Rights Reserved.