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.
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.
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:
where moduleName is the module that you wish to import.
To import class, the syntax is:
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:
The animal_def.py file contains a class as shown below:
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:
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:
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.
The code inside the file.py file will become
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,
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:
To import all the classes from a file inside a different file the syntax is
The * indicates all classes. So, to use both the classes inside the animal_def.py file inside the file.py file we can write:
Now, we can use both the classes inside the file.py file as if they were written inside it.
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:
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:
In this case, the syntax to import another class from a different directory becomes
So, in our case the import statement will be as follows:
Now, we can use the Animal class inside the file1.py file. Look at the sample code for the file1.py file below:
Let us take another example, suppose the directory structure is as follows:
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:
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:
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 ‘..’
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.