Skip to content

How does import work in Python?

Python is a high-level programming language used widely by developers across the globe. And, while working with Python, to use some package or python file, you import that package or file using the import statement. However, have you ever wondered how this import statement works? Let’s dive in to understand the working of the import statement in Python.

Also read: How to get file size in Python?


How to import a file in Python?

Let’s consider an example to understand how an import statement works when trying to import a python file. Suppose ‘ImportExample’ is a directory having three files ‘example1.py’, ‘example2.py’ and ‘example3.py’.

Code - example1.py
print("Hello, I am example 1.")

Code - example2.py
import example1.py
print("Hello, I am example2.")

Code - example3.py
print("Hello, I am example3.")
import example1.py

The output after running all the three files:

As you can see here, the output of the print statement of example1.py file is displayed with the output of the example2.py and example3.py based on the line where the import statement is present.
Therefore, when you import a python file, that file is executed, and its output is appended with the output of the file which imported the file.


How to import modules and packages in Python?

You import some modules or packages to use the functions, classes, or variables present in that module. When you specify the module’s name with an import statement, the standard built-in __import__() function is called. This function searches for the module in the system, and when found, it creates and initializes an object of that module. The function throws a ModuleNotFoundError when the function cannot find the module.

import math

Importing variables or functions from a module

If you want to use a specific variable or function from a module, you can only import that variable in place of the whole module.

from x import y

Here, x is the module name, and y is the variable or the function name. The __import__() function searches for the module and imports the specific variable or function into the code.

If you want to import all the modules’ contents, you use the ‘*’ operator.

from x import *

Importing submodules from a package

A module that has submodules is known as a package. You can import a submodule from a package using the “.” operator.

import p.q

The __import__() function first searches and imports the required submodule package. Then, it further searches inside the package for the submodule and then imports that submodule.

Also read: How to get the current working directory in Python?

Hello There!

If you like what you read, please support our publication by sharing it with your friends, family and colleagues. We're an ad-supported publication. So, if you're running an Adblocker, we humbly request you to whitelist us.







>