Importing Modules

Importing Single Module

PowerShell provides an Import-module cmdlet to import modules in the current session.

Import-Module ActiveDirectory

Whereas, Python has a keyword import to load modules into the current Python Session, but the import statement does not make contents in the module directly accessible to the caller and are only accessible when they are prefixed with <module name> followed by a (’ . ‘) dot notation: <module name>.<property/method> like in the following example.

import os print(os.getcwd())

Importing Multiple Modules

Both PowerShell and Python allows you to import multiple modules in the session by referencing the module names separated by (’ , ‘) comma(s), for example in Python the syntax would look something like import <module1>, <module2> ...

import time, sys time.sleep( 2 ) print( "Platform:" ,sys.platform)

Similarly, in PowerShell Import-Module cmdlet also follows almost the same syntax: Import-Module <module1>, <module2> ...

Import-Module PSReadLine, AzureRM, Posh-Git

Importing Sub-Modules

Python allows us to import only the sub-module(s) of a module, which are basically packages inside a Python module using the from ... import ... keywords.

from random import shuffle array = [ 1 , 2 , 3 , 4 ] shuffle(array) print( 'shuffled array:' , array)

or importing multiple sub-modules separated by commas.

from statistics import mean, variance, median, stdev

Programmers are also allowed to import all sub modules from a module, using the following syntax: from <module name> import *

from random import *

Module Aliases

Python also allows programmers to define alternate names or aliases of the modules. While importing a module use the as keyword in following syntax import <module name> as <alternate name> to define an alias or an alternative names, these are easy to use and you don’t have to type the complete name of the module while accessing module objects.

import math as m print(m.pi) print(m.e)

Just to summarize everything, following are number of ways to import a module in python:

import matplotlib import matplotlib.pyplot import matplotlib.pyplot as plt from matplotlib import pyplot from matplotlib import pyplot as plt

NOTE:

This is just a teaser content from my book in form of a blog post!

If you want to know more about Installing modules, Importing Module Aliases, Creating new Modules in Python and PowerShell and other more advanced topics on Modules?

Then read my book (below) which is still in progress, on lean publishing format.

Buy early, pay less, free updates!