Import module in Python with Examples

โšก Smart Summary

Import in Python lets one file reuse the variables, functions, and classes defined in another. A module is simply a .py file, while a package groups related modules inside a directory marked by an __init__.py file.

  • ๐Ÿ”˜ What is a module: A module is a single .py file holding variables, functions, or classes.
  • โ˜‘๏ธ import keyword: import loads an entire module; module_name.function_name calls its members.
  • โœ… Selective import: from module import name pulls in only the functions or variables you need.
  • ๐Ÿงช Aliases: import module as alias shortens long names; from module import * exposes everything.
  • ๐Ÿ› ๏ธ Packages and paths: __init__.py turns a folder into a package; sys.path lists the search locations.
  • ๐Ÿค– AI workflows: Machine learning projects import NumPy, pandas, and PyTorch as modules.

Import module in Python

The sections below explain modules, packages, the different import styles, and how absolute and relative imports work in Python.

What are the modules in Python?

A module is a file with Python code. The code can be in the form of variables, functions, or a defined class. The filename becomes the module name.

For example, if your filename is guru99.py, the module name will be guru99. With module functionality, you can break your code into different files instead of writing everything inside one file.

What is the Python import module?

A file is considered a module in Python. To use the module, you have to import it using the import keyword. The functions or variables present inside the file can be used in another file by importing the module. This functionality is available in other languages like TypeScript, JavaScript, Java, Ruby, etc.

How to create and import a module in Python?

Now we will create a module and import it into another file.

Here is the flow to create and import the module as shown in the screenshot:

Create and Import a Module in Python

Follow the steps given to create a module in Python.

The folder structure used to test the code is as follows:

modtest/
	test.py
	display.py	

Step 1) Create a file and name it test.py

Step 2) Inside test.py create a function called display_message()

Def display_message():
    return "Welcome to Guru99 Tutorials!"

Step 3) Now create another file display.py.

Step 4) Inside display.py import the module test.py file, as shown below:

import test

While importing, you do not have to mention the test.py but just the name of the file.

Step 5) Then you can call the function display_message() from test.py inside display.py. You need to make use of module_name.function_name.

For example test.display_message().

Import test
print(test.display_message())

Step 6) When you execute display.py, you will get the following Output:

Welcome to Guru99 Tutorials!

Importing a Class in Python

Earlier, we have seen a simple module with a function. Here we will create a class and refer to the class inside another file.

The folder structure to test the code is as follows:

myproj/
	Car.py
	display.py

Create a file called Car.py with the following code:

Filename : Car.py

class Car:
	brand_name = "BMW"
	model = "Z4"
	manu_year = "2020"

	def __init__(self, brand_name, model, manu_year):
		self.brand_name = brand_name
		self.model = model
		self.manu_year = manu_year

	def car_details(self):
		print("Car brand is ", self.brand_name)
		print("Car model is ", self.model)
		print("Car manufacture year is ", self.manu_year)
			
			
	def get_Car_brand(self):
		print("Car brand is ", self.brand_name)

	def get_Car_model(self):
		print("Car model is ", self.model) 

In the file Car.py, there are attributes brand_name, model and manu_year. The functions defined inside the class are car_details(), get_Car_brand(), get_Car_model().

Let us now use the file Car.py as a module in another file called display.py.

Filename : display.py

import Car
car_det = Car.Car("BMW","Z5", 2020)
print(car_det.brand_name)
print(car_det.car_details())
print(car_det.get_Car_brand())
print(car_det.get_Car_model())

Output:

BMW
Car brand is  BMW
Car model is  Z5
Car manufacture year is  2020
Car brand is  BMW
Car model is  Z5

So we can access all the variables and functions from Car.py using the Car module.

Using from to import module

You can import only a small part of the module, i.e., only the required functions and variable names from the module instead of importing the full code.

When you want only specific things to be imported, you can make use of the “from” keyword to import what you want.

So the syntax is

from  module import your function_name , variables,... etc.

The folder structure used to test the code is as follows:

modtest/
	test.py
	display.py	

In test.py there are 2 functions as shown:

Filename : test.py

defdisplay_message():
	return "Welcome to Guru99 Tutorials!"
	
def display_message1():
	return "All about Python!"

Now you want the display_message() function. The function or variable that you are importing can be directly accessed as shown below:

File Name : display.py

from test import display_message
print(display_message())

Output:

Welcome to Guru99 Tutorials!

Now if you happen to use the function display_message1(), it will throw an error that the function is not defined as shown below:

from test import display_message
print(display_message1())

Output:

Traceback (most recent call last):
File "display.py", line 3, in <module>
print(display_message1())
Name Error: name 'display_message1' is not defined

Importing everything from the module

Import allows you to import the full module by using import followed by the module name, i.e., the filename or the library to be used.

Syntax:

Import module

Or by using

from module import *

The folder structure used to test the code is as follows:

modtest/
	test.py
	display.py	

Following are the code details inside test.py

my_name = "Guru99"
my_address = "Mumbai"

defdisplay_message():
	return "Welcome to Guru99 Tutorials!"
	
	
def display_message1():
	return "All about Python!"

Using the import module

Using just the import module name, to refer to the variables and functions inside the module, you have to prefix them with the module name.

Example

Filename : display.py

Import test
print(test.display_message())
print(test.display_message1())
print(test.my_name)
print(test.my_address)

The module name test is used to refer to the functions and variables inside the module test.

Output:

Welcome to Guru99 Tutorials!
All about Python!
Guru99
Mumbai

Using import *

Let us see an example using import *. Using import *, the functions and variables are directly accessible, as shown in the example below:

from test import *

print(display_message())
print(display_message1())
print(my_name)
print(my_address)

Output:

Welcome to Guru99 Tutorials!
All about Python!
Guru99
Mumbai

The dir( ) function

The dir() is a built-in function in Python. The dir() returns all the properties and methods, including the given object’s built-in properties.

So when dir() is used on the module, it will give you the variables and functions that are present inside the module.

Here is a working example of dir() on a module. We have a class called Car.py, let us import Car and assign it to dir() to see the output.

The folder structure to test the code will be as follows:

test prop/
	Car.py
	test.py	

Filename: Car.py

class Car:
	brand_name = "BMW"
	model = "Z4"
	manu_year = "2020"

	def __init__(self, brand_name, model, manu_year):
		self.brand_name = brand_name
		self.model = model
		self.manu_year = manu_year

	def car_details(self):
		print("Car brand is ", self.brand_name)
		print("Car model is ", self.model)
		print("Car manufacture year is ", self.manu_year)
			
			
	def get_Car_brand(self):
		print("Car brand is ", self.brand_name)

	def get_Car_model(self):
		print("Car model is ", self.model) 

Filename: test.py

import Car

class_contents = dir(Car)
print(class_contents)

The output gives us the name of the class and all the functions defined in Car.py.

You can also try using dir() on a built-in module available in Python. Let us try the same on the json module as shown in the example below. It will display all the properties and methods available in the json module.

Import json
json_details = dir(json)
print(json_details)

Output:

['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__bu
iltins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__pac
kage__', '__path__', '__spec__', '__version__', '_default_decoder', '_default_en
coder', 'codecs', 'decoder', 'detect_encoding', 'dump', 'dumps', 'encoder', 'loa
d', 'loads', 'scanner']

Packages

A package is a directory with all modules defined inside it. To make a Python interpreter treat it as a package, your directory should have the __init__.py file. The __init__.py makes the directory a package. Here is the layout of the package that we are going to work on.

Packages in Python

The name of the package is mypackage. To start working with the package, create a directory called mypackage/. Inside the directory, create an empty file called __init__.py. Create 3 more files module1.py, module2.py, and module3.py and define the functions as shown in the screenshot. Here are the details of module1.py, module2.py and module3.py

module1.py

def mod1_func1():
print("Welcome to Module1 function1")

def mod1_func2():
print("Welcome to Module1 function2")

def mod1_func3():
print("Welcome to Module1 function3")

module2.py

def mod2_func1():
print("Welcome to Module2 function1")

def mod2_func2():
print("Welcome to Module2 function2")

def mod2_func3():
print("Welcome to Module2 function3")

module3.py

def mod3_func1():
print("Welcome to Module3 function1")

def mod3_func2():
print("Welcome to Module3 function2")

def mod3_func3():
print("Welcome to Module3 function3")

The package is ready for use. Now call the package inside any of your files as shown below in test.py:

Here, the mypackage.module1 is imported and given an alias name as mod1. Similarly, you can use the other modules module2.py and module3.py from mypackage.

import mypackage.module1 as mod1

print(mod1.mod1_func1())
print(mod1.mod1_func2())
print(mod1.mod1_func2())

Output:

Welcome to Module1 function1
None
Welcome to Module1 function2
None
Welcome to Module1 function2
None

We have just demonstrated the package with a simple module with functions inside it. As per your project, you can also create packages that have sub-packages, i.e., sub-folders having modules with classes defined.

Python Module Search Path

During execution, when Python comes across import module name, the interpreter tries to locate the module. It searches for the module in the built-in module list, and then in all the directories defined inside sys.path.

To sum up, the interpreter does the following search to locate the module:

  1. In your current directory.
  2. In the built-in module list.
  3. Inside the sys.path directories.

You can get the details of sys.path by importing the sys module and printing sys.path. It will give you the list of directories as shown below:

importsys
print(sys.path)

Output:

['Python Latest\\task2', 'Users\\AppData\\Local\\Programs\\Python\
\Python37\\python37.zip', 'Users\\AppData\\Local\\Programs\\Python\\P
ython37\\DLLs']

You can also modify the path and keep the directories as per your requirements.

Using module alias in the import

You can also convert the module name to a shorter form by giving it an alias name. The alias can be created using the as keyword.

Syntax:

import filename as alias name

The folder structure to test the code will be as follows:

Mod test/
	test.py
	display.py	

Following is the code inside test.py

my_name = "Guru99"
my_address = "Mumbai"

def display_message():
	return "Welcome to Guru99 Tutorials!"	
	
def display_message1():
	return "All about Python!"

Now we will use an alias for test.py in display.py

Import test as t

print(t.display_message())
print(t.display_message1())
print(t.my_name)
print(t.my_address)

The alias used for the test module is t. So the functions and variables from test.py can be referred to using the alias t.

Output:

Welcome to Guru99 Tutorials!
All about Python!
Guru99
Mumbai

Absolute and Relative Imports in Python

You now know how to import a file as a module inside another file. Let us now see how to manage the files available in folders. The files in the folders can be imported either by using absolute or relative imports.

Consider you have your project folder structure, as shown below:

Absolute and Relative Imports in Python

The root folder is myproject/. It has two subfolders package1 and package2.

The folder package1 has two modules, module1.py and module2.py.

The folder package2 has one class myclass.py, a sub-package subpkg with module3.py, and last module4.py.

  • In module1.py, there is a function called myfunc1.
  • In module2.py, there is a function called myfunc2.
  • In module3.py, there is a function called myfunc3.
  • In module4.py, there is a function called myfunc4.

Using Absolute Imports

For absolute imports, you need to add the entire path of your module right from the project root folder.

Let us now see how to make use of absolute imports to refer to the functions present in each of the modules.

To work with the function myfunc1, you will need to import it as follows:

from package1.module1  import  myfunc1
or
from package1 import module1
module1.myfunc1()  

To work with the function myfunc3, you will need to import it as follows:

from package1.subpkg.module3  import  myfunc3
or
from package1.subpkg import module3
module3.myfunc3()  

Advantages and Disadvantages of using absolute imports

Here are the advantages of using absolute imports:

  • It becomes easy to trace back the modules for code check.
  • Easy to use and very straightforward.
  • If the project is moved to a different path, the imports will still remain the same.

Disadvantages of using absolute imports

Here are the disadvantages of using absolute imports:

  • The import path can get very long in case the modules are nested and the module names are lengthy.

Using Relative Imports

Considering the same folder structure mentioned above, we will see how to import the same using relative imports.

In a relative import, the module to be imported is relative to the current location, that is, the location where the import statement is present.

Syntax

In relative imports, you need to add a period (.) before the module name when importing using from.

It will be two periods (..) before the module name if the module is one level up from the current location.

Referring to the folder structure figure mentioned above, we have the following modules with their functions, which we need to refer to.

  • In module1.py, there is a function called myfunc1.
  • In module2.py, there is a function called myfunc2.
  • In module3.py, there is a function called myfunc3.
  • In module4.py, there is a function called myfunc4.

To work with the function myfunc1, you will need to import it as follows:

from  .module1  import  myfunc1

To work with the function myfunc3, you will need to import it as follows:

from  .subpkg.module3  import  myfunc3

Advantages of Relative Imports

  • It is easy to work with relative imports.
  • From the current location, the imports can be shortened in comparison to absolute imports.

Disadvantages of Relative Imports

  • Using relative imports, it is difficult to trace back where the code resides.

FAQs

Python cannot locate the module. Confirm the file is spelled correctly, sits on sys.path or in the current folder, and the package is installed in your active virtual environment. Run pip install followed by the package name for third-party modules.

Install it first with pip, the Python package manager, for example pip install pandas. Once installed into your environment, import it normally with import pandas. Built-in modules like json need no installation.

A circular import happens when two modules import each other, leaving one only partially loaded. Fix it by merging shared code, importing inside the function that needs it, or importing the whole module instead of specific names.

That guard runs code only when the file executes directly, not when imported. Without it, every import would re-run the module top-level statements. It keeps reusable functions separate from script-style test code.

No. Python executes a module once, then caches it in sys.modules and reuses that object for later imports. To force a reload during development, call importlib.reload(module).

Use importlib.import_module(“name”) when the module name is known only while running, such as loading plugins. It returns the module object, so you can access its functions like a normal import.

Machine learning code imports NumPy, pandas, scikit-learn, TensorFlow, and PyTorch as modules. Teams also split their own pipelines into reusable modules and packages, then import shared preprocessing and training functions across scripts.

Yes. GitHub Copilot and agentic assistants suggest import lines as you type, add missing imports, and help resolve import errors. Always confirm the module is installed and the name matches your environment before trusting a suggestion.

Summarize this post with: