Importing a module in Python

 Importing a module

Modules

  • Modules have a namespace containing random python objects.
  • Modules are called into python by the importing process.
  • A module is a python code file. In this code we define variables, functions, or class.
  • Module used by the import keyword.
  • We can use function or variables of a module in other files or modules by  importing the module.

 Create and import a module in python

Use following steps:-

Step 1) create a file and name it m.py

 Step 2) create a function display() in m.py

                   def display():

    return "welcome in importing module topic!"

 Step 3) create another file show.py.

 Step 4) import the m.py module file in show.py:

                     import m

 Step5) call the function

Call the function display() from m.py inside show.py, as

Module_name.function_name.

Example:-     m.display().

Import m

Print(m.display())

 Step 6) execution result

Execute show.py,

Output:

Welcome in importing module topic!

 

Importing a class in python

Create a class and use this class inside another file.

Create a file called car.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) 

 

  • Brand_name, model and manu_year are attributes and car_details(), get_car_brand(), get_car_model() are functions in car.py.
  •  Use the file car.py as a module in another file called display.py.
  • Create a file display (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

 

Using from to import module

If import only a small part of the module i.e., only the required functions and variable names (only specific things ) from the module use the “from”  keyword to import.

Syntax:-

From  module import  function_name , variables,... Etc.

 

From m import display
Print(display())

Output:

Welcome in importing module topic!

 

Importing everything from the module

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

Syntax:

Import module

Or

From module import *

 

Example:

               m.py
               show.py 

Following are the code details inside test.py

My_name = "abc"
My_address = "bikaner"
 
Def display():

            return " welcome in importing module topic!"

Def display1():
               return "all about python!"

 

Example:- in file : show.py

Import m
Print(m.display())
Print(m.display1())
Print(m.my_name)
Print(m.my_address)

 

Output:

Welcome in importing module topic!
All about python!
Abc
Bikaner

 

Using import *

By using import *. Using import *, the functions and variables are directly accessible.

Example:- 
From m import *
 
Print(display())
Print(display1())
Print(my_name)
Print(my_address)

 

Output:

Welcome in importing module topic!
All about python!
Abc
Bikaner

 

Using module alias in the import

Convert the module name to a shorter form by an alias name. The alias can be used as keyword.

Syntax:

Import filename as alias name
Import m as x
 
Print(x.display())
Print(x.display1())
Print(x.my_name)
Print(x.my_address)

 

Output:

Welcome in importing module topic!
All about python!
Abc
Bikaner

 

Absolute and relative imports in python

Import a file as a module inside another file. The files in the folders can be imported either by using absolute or relative imports.

Example:-

Project folder structure


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, need to add the entire path of module right from the project root folder.

Ex.

Use the function myfunc1, need to import as follows:

From package1.module1  import  myfunc1
Or
From package1 import module1
Module1.myfunc1()  

Use the function myfunc3 , need to import as follows:

From package1.subpkg.module3  import  myfunc3
Or
From package1.subpkg import module3
Module3.myfunc3()  
 

Advantages of absolute imports:

  • 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 absolute imports

  • 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

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:

Use a period (.) Before the module name when importing using from.

Use 2 periods (..) Before the module name if the module is in the one level up from the current location.

Syntax: -
From  .module1  import  myfunc1

Example:- to work with the function myfunc3, then use:

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

 

Python module search path

Searches the module in the build-in module list. All the directories are defined inside sys.path.

The interpreter uses the following search for the location of the module:

  1. Current directory.
  2. In the build-in module list
  3. Inside the sys.path directories

Access the details of sys.path by importing sys module and printing the sys.path.

Import sys
Print(sys.path)

 

=================================================== 

Post a Comment

0 Comments