How to Import a Class from Another File in Python?

Photo of author

A class from another Python file or folder, you may need to import as you work on a Python project that calls for it. This tutorial examines how to import a class from another Python file.

The Python import keyword, similar to the C/C++ #, includes the header file, making it simple to import a class. Python modules can use the import command to have a file or function and access code from other modules.

More information about importing a class in Python from another file can be found by reading on.

Read also: What Is Python Extend Class: Things To Know

How to import a class from another file in Python?

In the following example, we will discuss importing a class from another file in Python and define a class in file1.py before importing it in file2.py.

How to import a class from another file in Python

application/module1/file1.py
Class ArithmeticOperations:
def __init__(self):
self.sum_ = 0
def get_sum(self,num1,num2):
self.sum_ = num1+num2
return self.sum_
application/module1/file2.py
import file1
obj = file1.ArithmeticOperations()
c = obj.get_sum(3,8)
print(c)

Output: 11

The “import” phrase was utilized in the example above to import file 1. After that, we use a reference to the class, in this case, Arithmetic Operations, to construct an instance. We may interpret it as;

It is what we can make of it: We added file 1 to our import list. Following that, we assign the class to the variable obj by referencing it using 

file1.ArithmeticOperations().

The get_sum method is then called using the ‘obj’ object. The result allocated to the variable “c” is then printed. Proceed to inspect it;

from file1 import ArithmeticOperations
obj = ArithmeticOperations()
print(obj.get_sum(9,11))

Output: 20

See also: Data Serialization In Python: Convert Python Dictionary To JSON

Import class from another file python (all class)

This section will discuss importing a class from another file, Python (all classes). It may be necessary to import all the classes from different files. In such a case, you would say “from file_name> import *.” We can view that as importing all from file_name. It indicates that we imported all of the classes from the provided file.

Python File

Let’s examine its illustration.

application/module1/file1.py
class ArithmeticOperations:
def __init__(self):
self.sum_ = 0
def get_sum(self,num1,num2):
self.sum_ = num1+num2
return self.sum_
class PrintData:
def __init__(self):
self.data = ""
def print_data(self,data):
self.data = data
return self.data
application/module1/file2.py
from file1 import *
obj1 = ArithmeticOperations()
print(obj1.get_sum(9,11))
obj2 = PrintData()
print(obj2.print_data("Accessing Another class from file1"))

Output: 20 Accessing Another class from file1

Import class python from another folder

In this example, we’ll utilize the file3.py class for arithmetic operations in the module1 folder. However, before we can accomplish that, module 1 must have the __init__.py file, which notifies the interpreter that the module is part of the same package.

Additionally, we need to mention module 1’s path. We’ll make use of the “sys” module for that.

Examine the code now.

import sys
sys.path.insert(0,"..")
from module1.file1 import ArithmeticOperations
obj = ArithmeticOperations()
print(obj.get_sum(8,23))

Output: 31

‘sys.path.insert(0,”..”) ‘This line of code instructs the interpreter first to leave the current directory and go to the parent directory, where it should search for the module.

Read also: Measuring Performance In Python With The Timeit Module

Import classes from predefined libraries

We used “import sys” in the example above since it is a predefined library we wish to import and use for its functions.

It is clear from the syntax sys.path.insert() that we wish to use the insert function from the path class, which is part of the sys module. Using these dependencies and modules simplifies our process because we don’t have to code directly for these functions. 

Import class from another file python in a different directory

You must adhere to a slightly distinct syntax than what was previously described to import the class from a file in another directory.

Import class from another file python in a different directory

Two methods exist for doing this:

Indicate a directory without an external library

Without utilizing an external library, you can define the path in the import statement precisely as it is.

The following is the syntax:

from folder_name.file_name import class_name

The __init__.py file, found in any folder, can import a class using this syntax. Therefore, put the file __init__.py in the same directory as the class import file before attempting to import the class from a folder.

The __init.py file can be empty. Lacking one, you won’t be able to import modules into your project from another place.

Read also: How To Send HTML Emails With Python 

Using the sys library

By default, Python searches for modules in the current directory and the directories specified in the PYTHONPATH environment parameter. Utilize the sys.path list to add the directory to the Python search path if the module you wish to import is in another directory.

sys library

While searching for modules to import, Python searches across the collection of directory paths in the sys.path list. You are using the sys.path.append() method, you can add the path to the directory that contains the module you wish to import.

Assume that the library directory at the address /path/to/library contains a file with the name sample.py. To import the sample file into another Python script that is in a separate directory, follow these instructions:

  1. Importing the sys module will provide access to some parameters that the interpreter uses or maintains, as well as functions that have a close working relationship with the interpreter.
import sys

2. To the sys.path list, add the path to the directory that contains the module you wish to import.

sys.path.append('/path/to/library')

3. Use the module as usual after importing it.

Python may now find the sample module by adding the path to the sys.path list, and you can utilize it in your code. Be aware that when adding a directory to sys.path, you can also use relative paths, like in:

sys.path.append('/path/to/library)

The directory-storing module will be added to the search path if the working directory is one step higher than the directory for my project.

See also: True Or False? Understanding Python Boolean Variables

Why is it essential to Python import a class from another file?

It is an excellent question, to be sure. As already said, writing lengthy programs results in complex, difficult-to-understand code. Programmers commonly use modular approaches to create more readable, understandable code.

According to the modular programming paradigm, we should divide a complex problem into several smaller ones rather than writing code for only one. Once we’ve resolved them, we’ll combine them to accomplish our primary objective.

Using a modular strategy improves the code’s usability. It implies that a function can contain a group of statements repeated multiple times throughout the code and can be called anytime those particular sets of words must be executed. We can easily manage them with this method and change them to suit our needs. Furthermore, since we do not have to fiddle with various files, it significantly helps us debug our program.

Therefore, import statements are necessary to adopt a modular strategy.

FAQs

What function does Python's _ init _.py serve?

Python __init__.py can be used to convert directories into modules.

How can a class from a different Python file in the same directory be imported?

Create a file called __init__.py in this directory to import from the exact location. It would suggest a successful import.

How may a class from another Jupyter notebook be imported?

# Execute the following command !pip install ipynb

What is the import statement in Python?

The import statement in Python makes it easy to add code from other files or modules to the file we're working on. Consider it a bridge that enables us to use class properties or methods from other files.

Conclusion

We hope this article about importing a class from another file Python is helpful. No matter the language, importing classes and modules is the fundamental building block of programming. Therefore, be careful to understand this idea entirely. 

Check this out: Python Basics: Understanding Identifiers In Python

Leave a Comment