Import a Class from Another File in Python

By James L.

In this guide, we will cover the following topics:

  1. Importing a class from another file in the same directory
  2. Importing a class from another file in a different directory

# Importing a class from another file in the same directory

You can use the import statement to import a class from another file in Python.

Let’s consider a file named my_module.py with the following content:

# my_module.py

class MyClass:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, {self.name}!")

Now, you can import the MyClass class into another Python file, let’s call it main.py, like this:

# main.py

from my_module import MyClass

# Create an instance Of MyClass
obj = MyClass("James Bond")

# Use the method of the MyClass
obj.greet()  # Hello, James Bond!

In this example, main.py imports the MyClass class from my_module.py using the from my_module import MyClass syntax. After importing, you can create an instance of MyClass and use its methods as needed.

Ensure that the files are in the same directory or that the module’s directory is in the Python path. If the files are in different directories, you may need to use relative or absolute imports or modify the Python path accordingly.

Importing multiple classes from a single file

To import multiple classes from a single file, simply separate their names with commas as follows:

from my_module import MyClass1, MyClass2, MyClass3

This statement imports MyClass1, MyClass2, and MyClass3 from the my_module module. After importing, you can utilize these classes in your code just like any other class.

Importing all classes from a single file

To import all classes from a single file, you can use the asterisk * wildcard character with the import statement.

from my_module import *

This statement imports all classes defined in the my_module file. However, keep in mind that using the wildcard import is generally discouraged in larger codebases because it will make the code less readable and may lead to naming conflicts. It’s often better to explicitly list the classes you need to use.

# Import class from another file in a different directory

If the files are in different directories, you need to use relative or absolute imports or modify the Python path accordingly. 

Suppose you have the following directory structure:

project_directory/
│
├── main.py
└── modules/
    ├── __init__.py  #Empty file
    └── my_module.py

First, create an empty file __init__.py in the directory you want to import from. This marks the directory as a Python package, enabling imports from it.

Relative imports

To import MyClass from my_module in main.py, which is in a different directory, you can use the relative import like this:

from modules.my_module import MyClass

# Create an instance of MyClass
obj = MyClass("James Bond")

# Use the method of MyClass
obj.greet()  # 'Hello, James Bond!'

In this example, main.py and my_module.py are in different directories, but they share a common parent directory (project_directory). The import statement from modules.my_module import MyClass demonstrates relative import because it specifies the module (my_module) relative to the current module (main).

Absolute imports

You can use absolute imports by modifying the Python path. This is typically done by appending the path to your module to the sys.path list.

Here’s an example:

from modules.my_module import MyClass
import sys
sys.path.append('path/to/project_directory')

# Create an instance of MyClass
obj = MyClass("James Bond")

# Use the method of MyClass
obj.greet()

Replace path/to/project_directory with the actual path to your project directory. This method allows you to import modules from any location in your project.

You can also dynamically get your project directory as shown in the code below:

from modules.my_module import MyClass
import os
import sys

# Get the absolute path of the current script
current_script_path = os.path.abspath(__file__)

# Get the directory of the current script (main.py)
project_directory = os.path.dirname(current_script_path)

# Add the project directory to the Python path
sys.path.append(project_directory)


# Create an instance of MyClass
obj = MyClass("James Bond")

# Use the method of MyClass
obj.greet()

Ensure the current script (main.py) is in the project_directory.

It is generally a good practice to use relative imports for intra-package imports within your project, and absolute imports for external libraries or when working with multiple projects. Modifying the Python path should be done cautiously, as it can lead to unexpected behavior in certain situations.

Conclusion

In conclusion, this guide has provided a comprehensive overview of how to import a class from another file in Python, covering scenarios within the same directory and in different directories.

We have explored the use of the import statement and discussed importing single or multiple classes.

We explored both relative and absolute imports to import classes from a file in a different directory. 

Use relative imports for intra-package imports within a project and use absolute imports for external libraries or when working with large projects. 

By following these guidelines, you can effectively manage class imports, creating a more organized and structured Python code.