Import module in Python with Examples

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 class defined. 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 as a module in python. To use the module, you have to import it using the import keyword. The function 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 in 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 moduletest.py file, as shown below:

import test

While importing, you don’t 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 will create a class and refer 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 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 full code.

When you want only specific things to be imported, you can make use of “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 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 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 import module name, to refer to the variables and functions inside the module, it has to prefix with 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 function and variables inside 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, 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 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 json module as shown in the example below. It will display all the properties and methods available in 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.pyfile. The init.py makes the directory as 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 my package. To start working with the package, create a directory called package/. 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 packages ready for use. Now call the package inside any of your file as shown below :test.py:

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

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 package with have sub-packages. 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 the module in the build-in module list. Later 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 in the build-in module list
  3. Inside the sys.path directories

You can get the details of sys.path by importing sys module and print the 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 an alias name to it. The alias can be done using the 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 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 that is used for test module is t . So the function and variables from test.py can be referred 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 my project/. 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 functioncalledmyfunc1.
  • In module2.py, there is a functioncalledmyfunc2.
  • In module3.py, there is a functioncalledmyfunc3.
  • In module4.py, there is a functioncalledmyfunc4.

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 module.

To work with the functionmyfunc1, you will need to import 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 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, still the imports will remain the same.

Disadvantages of using absolute imports

Here, are disadvantages of using absolute imports:

Disadvantages:

  • The import path can get very long in-case, the modules are nested, and if the name of the modules is lengthy.

Using Relative Imports

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

In 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 2 periods (..) before the module name if the module is in the one level up from the current location.

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

  • In module1.py, there is a functioncalledmyfunc1.
  • In module2.py, there is a functioncalledmyfunc2.
  • In module3.py, there is a functioncalledmyfunc3.
  • In module4.py, there is a functioncalledmyfunc4.

To work with the functionmyfunc1 you will need to import as follows:

from  .module1  import  myfunc1

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

from  .subpkg.module3  import  myfunc3

Advantages of Relative Imports

Advantages:

  • 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

Disadvantages:

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

Summary

  • Import in Python helps you to refer to the code, i.e., .functions/objects that are written in another file. It is also used to import python libraries/packages that are installed using pip(python package manager), and you need then to use in your code.
  • Import functionality is available in other languages like typescript, JavaScript, java, ruby, etc.
  • A module is python is the code written inside the file, for example (test.py). Inside your file, you can have your variables, functions, or your class defined. The entire file becomes a module and can be imported inside another file to refer to the code.
  • With module functionality, you can break your code into different files instead of writing everything inside one file. Later, using import, you can refer to the code inside the file you need.
  • Python has its built-in modules, and also external libraries/packages installed using a python package manager (pip), e.g., pandas, NumPy, etc. are referred to as modules.
  • 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 full code.
  • You can also convert the module name to a shorter form by giving an alias name to it. The alias can be done using the keyword.
  • 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.pyfile. The init.py makes the directory as a package. Here is the layout of the package that we are going to work on.
  • During execution, when python comes across import module name, the interpreter tries to locate the module. It searches the module in the build-in module list. Later in all, the directories defined inside sys.path.
  • For Absolute imports, you need to add the entire path of your module right from the project root folder.
  • In relative import, the module to be imported is relative to the current location that is the location where the import statement is present.