How to Import Other Python Files

09/11/2021

Contents

In this article, you will learn how to import other Python files.

Import Other Python Files

In Python, you can import other Python files (also known as modules) into your script to reuse code and make your project more modular and organized. There are a few different ways to do this, including:

Using the import statement

For example, if you have a module named example_module.py, you can import it into your script with the following statement:

import example_module
Using the from … import … statement

For example, if the example_module has a function named example_function, you can import it into your script with the following statement:

from example_module import example_function
Using an alias with the import … as … statement

For example, if you have a module named example_module.py, you can import it into your script with the following statement:

import example_module as em

Once you have imported a module, you can use the functions and classes defined in the module by referencing them using the module name or alias.

Here are a few additional details that might be useful to know when working with Python modules:

Location of modules

When you import a module, Python will search for it in a few different places, including the current directory, the directories listed in the sys.path list, and the standard library directories. If the module is not found in any of these locations, Python will raise an ImportError.

Namespaces

When you import a module, its functions, classes, and variables become part of the global namespace of your script. This means that you can access them using the module name (or alias) followed by a dot (.) and the name of the function, class, or variable. For example, if you have imported a module named example_module and it contains a function named example_function, you can call the function with example_module.example_function().

Reloading modules

Sometimes, you might make changes to a module that you have already imported into your script. To ensure that your script is using the latest version of the module, you can use the reload function from the importlib module. For example:

import importlib
importlib.reload(module_name)

This will reload the module and make any changes that you have made to the module available to your script.