How to Import Other Python Files

Python is an open-source programming language that is widely used for various purposes such as scientific computing, web development, and data analysis.

One of the key features of Python is its ability to import other Python files, making it easy for developers to reuse code and build complex applications.

In this tutorial, we will explore the different ways to import other Python files in your project.


Ways to Import Other Python Files

Import Statement

The simplest way to import other Python files is by using the import statement.

The import statement allows you to import the module or package into your current Python file, giving you access to its functions and classes.

Here is an example of how to import a module named “example_module” in your Python file:

import example_module

From Statement

The “from” statement is similar to the import statement, but it allows you to import specific functions or classes from the module into your current Python file.

Here is an example of how to import a function named “example_function” from the module “example_module”:

from example_module import example_function

As Statement

The “as” statement allows you to give a module or function an alias.

This can be useful if you want to import a module or function with a different name in your Python file.

Here is an example of how to import a module named “example_module” with an alias “em”:
python

import example_module as em

Relative Imports

Relative imports allow you to import modules or packages that are located in the same directory as your current Python file.

Here is an example of how to import a module named “example_module” located in the same directory as your current Python file:

from . import example_module

Absolute Imports

Absolute imports allow you to import modules or packages located in other directories. Absolute imports can be done using the full path of the module or package.

Here is an example of how to import a module named “example_module” located in a directory named “example_directory”:

from example_directory import example_module

Conclusion

In conclusion, importing other Python files is a crucial aspect of Python programming, allowing developers to reuse code and build complex applications.

With this tutorial, you now have a good understanding of the different ways to import other Python files in your Python projects.