What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Import Class from Another File

  • Jul 28, 2022
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Riddhima Agarwal
Python Import Class from Another File

A time may come in your coding journey when you will be writing a very complex code and things will stop making sense. Your program will be tangled in such a complicated manner, that you will be confused and will sit staring at the screen as to where to move forward from here on.  What experienced programmers do in such a situation is that they divide the whole program into chunks or modules and then put them into different files. In doing so, they reduce the program complexity, making it easy for them to debug and identify errors. For using a class or method, stored in a different python file we need to import the class into our working file. 

In this article, we are going to make you familiar with the process of importing a class from another file in python. But before diving straight into importing classes, let us clear some basics.

What is a Class in Python?

A class is a blueprint or prototype that is defined by the user and used to build things. Classes allow you to group data and functionality together. A new class introduces a new type of object, allowing for the creation of new instances of that type. Each instance of a class can have attributes linked to it to keep track of its status. Class instances can additionally have methods for changing their state (specified by their class).

Consider the following situation: We want to keep track of the customers in a hotel. So, each customer will have some common properties like name, age, date of birth, date of check-in, date of check out, etc. But the values of these properties will be different for each customer. We hence create a blueprint for customers staying in our hotel and then create instances of the customer class which will enable us to store specific property values for each customer. 

Also, Learn how to get a class name in python.

A class creates a user-defined data structure with its own data members and member methods that can be accessed and utilized by establishing a class instance. A class is similar to an object's blueprint.

Why do We Need to Import a Class from Another File in Python?

Now, this is a very good question. As discussed above when writing long programs, the code tends to get complex and difficult to understand. Hence to increase the readability and understandability of the code, programmers often follow a modular approach.

Modular programming is a programming paradigm in which instead of developing code for a single large problem, we break it down into multiple smaller ones. We'll put them all together once we've solved them all to reach our main goal.

Following a modular approach increases the reusability of the code. This means a set of statements that are repeated various times inside the code can be put inside a function, and that function can be called whenever those sets of statements need to be executed. This approach makes it simple for us to manage them and make modifications based on our needs. Furthermore, it really aids us in debugging our program because we do not have to mess with multiple files.

Therefore, to implement a modular approach we require import statements.

How to Import Class from Another File in Python?

If you are familiar with the C++ programming language then you must have noticed #include lines in C++, the #include line does the very same that the import statement achieves in python. It allows us to use functions and classes kept in some other file inside our current code.

Python provides us with various ways in which we can import classes and functions using the import statements.

Import Statement

Now a little description of the import statement. The import statement allows us to import code from other files or modules into the current file. You can consider it as a link that allows us to access class properties or methods from other files and use them.

The syntax of import statements is as follows:

import moduleName

 

where moduleName is the module that you wish to import.

To import class, the syntax is:

from fileName import className

 

Here filename is the name of the file from which we wish to import a class and className is the name of the class to be imported

Importing classes from another file in the same folder

Imagine we have to following directory structure:

Main
  |-- animal_def.py
  |-- file.py

 

The animal_def.py file contains a class as shown below:

class Animal:

    def print_animal(self):
        return 'This is animal class'

 

Now to use this class inside the file file.py we need to use the second syntax mentioned above, which in this case will become:

From animal_def import Animal

 

Now the class is included in the file.py file. Imagine the code of the Animal class being copy-pasted into the file.py. We can now use it as a normal class inside the file.py file. So, the code inside the file.py will look something like this:

#file.py
# import Animal class
from animal_def import Animal

# create object of class
animal = Animal()

# call class method
print(animal.print_animal())

 

Output:

This is animal class

 

Since here we are importing from a file that is present in the same directory, therefore, we can import class Animal using the following statement as well.

import animal_def

 

The code inside the file.py file will become

#file.py
# import Animal class
import animal_def

# create object of class
animal = animal_def.Animal()

# call class method
print(animal.print_animal())

 

Output:

This is animal class

 

Notice how here the full path to the class needs to be provided in order to access it.

Note: You can import more than one class from the same file in python by separating the class names by commas. For example,

From FileName import class1, class2, class3, ………

 

Import all the classes from another file in the same folder

Here we will use the same directory structure, which was used in the previous case. But the code in the animal_def.py file is updated to contain the following code:

 

class Animal:
    def print_animal(self):

        return 'This is animal class'

class Reptile:
    def print_reptile(Self):
        return " This is reptile class"

 

To import all the classes from a file inside a different file the syntax is

From filename import *

 

The * indicates all classes. So, to use both the classes inside the animal_def.py file inside the file.py file we can write:

From animal_def import *

 

Now, we can use both the classes inside the file.py file as if they were written inside it.

For Example:

#file.py
# import all classes
from animal_def import *

# create object of Animal class
animal = Animal()

# create object of Reptile class
reptile = Reptile()

# call class method
print(animal.print_animal())
print(reptile.print_reptile())

 

Output:

This is animal class
This is reptile class

 

The use of the * sign might not seem very significant at this point of time because the animal_def.py file contains only two class definitions. Imagine what a tedious task it might have become to import all the classes by name if the file had contained tens of class definitions. That is when the * sign comes in handy.  

Importing classes from another folder

Many times it happens that the file we wish to import from is not present in our current working directory. Suppose that the directory structure is as follows:

main
  |-- module
    |-- human_def.py
  |-- run.py

 

Now, to be able to use the animal_def.py file’s classes inside the file1.py file, first we need to add a file named __init__.py inside the module folder. This file informs the python interpreter that the module folder is a package containing files that have class definitions. This file can be left empty.

The updated directory structure becomes:

main
  |-- module
    |-- human_def.py
|-- __init__.py |-- run.py

 

In this case, the syntax to import another class from a different directory becomes

from directory.fileName import className

 

So, in our case the import statement will be as follows:


From module.human_def import Animal

 

Now, we can use the Animal class inside the file1.py file. Look at the sample code for the file1.py file below:

#file.py
# import all classes
from module.animal_def import *

# create object of Animal class
animal = Animal()

# create object of Reptile class
reptile = Reptile()

# call class method
print(animal.print_animal())
print(reptile.print_reptile())

 

Output:

This is animal class
This is reptile class

 

Let us take another example, suppose the directory structure is as follows:

main
  |-- module
    |-- module1
      |-- human_def.py
      |-- __init__.py
  |-- run.py

 

In this case, to be able to use the Animal class inside the file1.py file, we need to use the complete path for the file with the names of the directories separated by the dot operator. So the import statement, in this case, will look as follows:

From module.module1.human_def import Animal

 

Another important point here is that the __init__.py file need not to be included in both the folders, it just needs to be present in the parent folder.

Importing classes from a different folder using the sys module

Imagine the directory structure as follows:

main
  |-- module
    |-- human_def.py
    |-- __init__.py
  |-- module2
    |-- file1.py

 

In this case, we will need to use a predefined library called sys. Then we use the sys.path.insert() module to tell the Python interpreter to where to look for the module. So we need to tell the interpreter to look at the directory above the current directory, therefore, we use ‘..’

For Example:

#file.py

# import sys module
import sys
# tell interpreter where to look
sys.path.insert(0,"..")

# import all classes
from module.animal_def import *

# create object of Animal class
animal = Animal()

# create object of Reptile class
reptile = Reptile()

# call class method
print(animal.print_animal())
print(reptile.print_reptile())

 

Output:

This is animal class
This is reptile class

 

Conclusion

Importing classes and code from another file allows us to implement a very important aspect of good programming called modular programming. In this article, we saw how to import classes within the same directory as well as a different directory. Importing classes and modules is the very basis of programming irrespective of the language. So make sure that you are thorough with this concept. If you have more doubts then reach out to our online python tutors who are available 24/7.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Riddhima Agarwal
Hey, I am Riddhima Agarwal, a B.tech computer science student and a part-time technical content writer. I have a passion for technology, but more importantly, I love learning. Looking forward to greater opportunities in life. Through my content, I want to enrich curious minds and help them through their coding journey