How to Import a Class or Module From Another File in Python?

How to Import a Class or Module From Another File in Python? - GuidingCode

You might be working on a Python project requiring you to import a class or module from another Python file or folder. This task is fairly common amongst developers as there might be instances where one wants to factor their code to stay organized.

Organizing code into files with their purpose is an important practice that allows developers to debug the code quicker and reduce the effort it will take to resolve issues. Apart from the need to organize the code, another need for importing a class is when one is working with a code they haven’t written and want to use certain functionality.

In this article, I will go over the basic ways of importing a class from another file in Python and the common issues you might encounter.

 

 

Importing a Class From a File in the Same Folder

You can easily import a class in Python using the import keyword, the equivalent of #include the header file in C/C++. Python modules can access code from other modules using the import command to include the file or function.

Import a class or module from another file or folder in python

 

The most popular import mechanism method is an import statement, although it is not the only method. The import keyword and the module’s name make up the import statement.

To import the class from a file, the syntax is as follows:

import file_name

 

To import a particular class from the file, the syntax is as follows:

from file_name import class_name

 

I will explain the use of the import statement using some Python code.

The code written below is from a file that you can create named sampleClass.py:

class QuickCalc:

# simple addition
def addition(self, a, b):
return a + b

# simple multiplication
def multiply(self, a, b):
return a * b

# simple subtraction
def subtraction(self, a, b):
return a - b

 

In the code above, I have defined a class called QuickCalc which contains three member functions which perform three different functionalities. These member functions can easily be accessed using the instance of the class.

The following code is present in the main.py. It can, however, be in any file where you want to use the imported class in.

import sampleClass
instance = sampleClass.QuickCalc()
total = instance.addition(2, 2)
product = instance.multiply(3, 4)

 

In the code above, you can see that using the import statement or keyword, I have imported the class from the file sampleClass.py and then created an instance of that class using the file name and performed some sample calculations, demonstrating the use of the class after importing.

If you want to import all the classes from a file, then the syntax is as follows:

from file_name import *

 

The ‘*’ character is used to signify that all classes need to import.

It is crucial to note that using the * wildcard character to import all classes is not advised because it can result in naming conflicts and make the code challenging to read.

Another way of importing a class is using an alias. There are situations where one might need to ‘re-name’ a class, and instead of renaming, you can import the class with an alias.

To import the class with an alias, simply use the syntax below:

from file_name import class_name as alias_name

 

 

Importing a Class From a File in a Different Directory

You might want to import a class from a file that is located in a different directory. To import the class from a file in a different directory, you must follow a slightly modified syntax than what was explained above.

Import a class or module from another file in a different folder or directory in python

 

There are two ways to do this:

 

1. Specify the Directory Without an External Library

You can specify the directory in the import statement as it is without using any external library. The syntax is as follows:

from folder_name.file_name import class_name

This syntax can be used to import a class from a file located inside of any folder where a file __init__.py is located. So before trying to import the class from a folder, make sure to add the file __init__.py in the same directory as that file.

The Python interpreter is informed that a directory contains code for a Python module by the __init .py file. A file named __init .py may be empty. You will be unable to import modules into your project from another location without one.

 

 

2. Using the Sys Library

Python by default searches the directories given in the PYTHONPATH environment variable as well as the current directory for modules. If the module you want to import is in a different directory, you must use the sys.path list to add that directory to the Python search path.

Python looks through a list of directory paths in the sys.path list when looking for modules to import. The sys.path.append() method allows you to add the path to the directory containing the module you wish to import to the sys.path list.

Assume you have a file named sample.py in the library directory at the address /path/to/library. Use these steps to import the sample file into another Python script that is placed in a different directory:

  1. Import the sys module, which provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
import sys
  1. Append the path to the directory containing the module you want to import to the sys.path list.
sys.path.append('/path/to/library')
  1. Import the module and use it as usual.

 

By appending the path to the sys.path list, Python can now find the sample module and you can import and use it in your code.

Note that you can also use relative paths when appending a directory to sys.path, for example:

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

 

If the current working directory is one level above the my project directory, this would add the directory containing the my module module to the search path.

 

 

Conclusion

In conclusion, if you want to import a class from a file in python, there are multiple ways you can try this, described above. You can use a import statement and with that statement can either import within the same folder or from another directory. Apart from this, you can use the help of the sys library to assist in importing the class.

Feel free to share this article with any of your fellow developers!

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
0
Share