StackTips

Python: Modules and Packages

stacktips avtar

Written by

Editorial,  4 min read,  2.01K views, updated on Sept. 17, 2023

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

Getting Started with Spring Boot: A Beginner's Guide

This course covers the fundamentals of Spring Boot an you will gain the necessary skills to develop various types of applications using the powerful features of the Spring Boot framework.

>> CHECK OUT THE COURSE

Continue reading..