DevOps | Scripts | Automation

Python

How to import module in Python?

Import a module in Python

As we know to work with any functions or class of that module, we need to install and import that module. To import a module in Python programming language, the import command is used.

For example,

import math

The above command will import the math module from the Python-installed libraries. Let’s import the Azure identity module to work with Azure authentication.

If the “azure.identity” module is not installed previously then the import will fail. To check which all installed modules you can directly import, run the help(‘modules’) in the Python terminal.

help('modules')

You will see the list of modules that can be imported.

Install packages

Alright, before using any module, you first need to install that package. There are a plethora of packages and libraries available for Python but to use them we first need to install them. You can search for the packages here: https://pypi.org/

If you have a python 3.x you can use the below command to install the package. Here we will use azure.identity module. Make sure you run the below command from a terminal like cmd or Powershell.

pip3 install azure.identity

For lower versions, you can run

pip install azure.identity


Import modules

Once you have installed the package, you can import certain modules to work with it. To import a module from the package use the below command.

from azure.identity import AzureCliCredential

From keyword is used for the package name and the import keyword is used for the module to import from the package.

To import more than one module, provide comma-separated module names.

from azure.identity import AzureCliCredential, AzurePowerShellCredential

if you need to import all modules then provide * instead of the specific module name.

from azure.identity import *

You can refer to the imported module with the other name using the “as” keyword and use it. In the below example, we will refer ceil class as c from the math package.

from math import ceil as c
print(c(10.5))

Loading