StackTips

Python: Modules and Packages

Updated On: Sep 17, 2022

In Python, a file containing statements and definitions is referred as a module.

All the methods and variables defined in a Python module can be imported and accessed from another modules.

Let us create a module for performing the math.py.

# Python Module example
def add(a, b):
   return a + b

def subtract(a, b):
   return a - b

def multiply(a, b):
   return a * b

Here, we have defined three functions inside the math module.

How to Import a Module in Python?

To import a module you need to use import statement

import math

sum = math.add(5, 10)
print("Sum is:", sum)

sum = math.subtract(15, 10)
print("Sub is:", sum)

Output:

Sum is: 15
Sub is: 5

You can also import the module by renaming as follows:

import math as m

sum = m.add(5, 10)
print("Sum is:", sum)

sum = m.subtract(15, 10)
print("Sub is:", sum)

Notice that in the above example, we have imported the entire module. Let's say you only wanted a specific function inside the module. We can do that too, like so:

from math import add
from math import subtract

sum = add(5, 10)
print("Sum is:", sum)

sub = subtract(15, 10)
print("Sub is:", sub)

Python Built-in Modules

Python has many built-in modules, and we've already used one extensively in this class, namely the math module.

Here are some other popular useful built-in modules that might be familiar to you:

arraycopyhtmlhttp
emailfileinputiojson
gcgzipipaddressnumbers
pippipesrandomssl
stringsymbolsystime

Definitely check out the documentation for these modules if you're curious about what functionality any of them offer!

References