Python modules. We’ll learn how to make our basic module, how to import Python modules, and how to give modules different names using ‘alias’.

What is the Module?

A Python module is a file that holds Python instructions and definitions. Inside a module, you can have functions, classes, variables, and even executable code.

Putting similar code together in a module helps us understand and use it better. It also keeps the code logically organized.

Create a Module

To make a Python module, write your code and save it in a file with the .py extension.

Let’s clarify this with an example:

Let’s make a simple calc.py file where we have two functions: one for add and another for subtract.


# This is a simple module named calc.py
def add(a, b):
"""
Function to add two numbers.
"""
return a + b
def subtract(a, b):
"""
Function to subtract two numbers.
"""
return a - b

Import module

We can use the import statement in one Python file to import functions or classes from another module. When you use the import command, the Python module checks if the module exists in the search path.

Note: The search path is a list of folders where the program looks for the module to import.

In simple terms, if you want to use or include the calc.py module in your script, you start your script by writing the following line at the very top:

Syntax:

import module
Note: When you use import calc, it doesn’t immediately bring in the individual functions or classes from the module. Instead, it only imports the entire module. To utilize specific functions or classes from this module, you’ll need to use the dot (.) operator.

Example:

Now, we’re using the calc module we previously made to execute an addition operation.


# importing module calc.py
import calc
print(calc.add(20, 2))

Output:

22

Import From Module

The from a statement in Python allows you to import specific attributes from a module without importing the entire module. Import Specific Attributes from a Python module

Here, we are importing only the sqrt and factorial attributes from the math module.

Example:


# Importing the specific functions sqrt and factorial from the math module.
from math import sqrt, factorial
# Using the imported functions directly without referencing the math module.
print(sqrt(9)) # Outputs the square root of 9, which is 3.
print(factorial(9)) # Outputs the factorial of 9, which is 362880.

Output:

3.0
362880

Import all Names

The * symbol in the import statement brings all names from a module into the current space.

Syntax:

from module_name import *

What does import * do in Python?

Using * has its advantages and disadvantages. If you’re sure about what you need from the module, avoid using *, but if you’re uncertain, go ahead.

Example:


# Importing the specific functions sqrt and factorial from the math module.
from math import sqrt, factorial
# Using the imported functions directly without referencing the math module.
print(sqrt(9)) # Outputs the square root of 9, which is 3.
print(factorial(9)) # Outputs the factorial of 9, which is 362880.

Output:

3.0
362880

Here, sys.path is an inherent variable found in the sys module. It lists the directories that the interpreter will scan to find the specified module.

Finding Python Modules

When Python imports a module, it searches in specific places. Initially, it checks for built-in modules. If not found there, it examines directories listed in the sys.path. The Python interpreter follows this sequence when searching for a module:

  1. Initially, it looks in the current directory for the module.
  2. If the module isn’t found in the current directory, Python examines each directory specified in the PYTHONPATH environment variable. PYTHONPATH contains a list of directories.
  3. If the module is still not found, Python checks the installation-specific list of directories that were set up during the Python installation process.

Directories List for Modules

Here, sys.path is an inherent variable found in the sys module. It lists the directories that the interpreter will scan to find the specified module.

Example:


# Importing the sys module
import sys
# Displaying the directories in sys.path
print(sys.path)

Output:

Directories List for Modules

Renaming the Module

We can give a different name to a module during the import process using a specific keyword.

Syntax:

Import Module_name as Alias_name

Example:


# Importing the sqrt() and factorial functions from the math module and assigning an alias 'mt' to it.
import math as mt
# Using the sqrt() function from the 'mt' module to find the square root of 16.
print(mt.sqrt(9))
# Using the factorial() function from the 'mt' module to compute the factorial of 6.
print(mt.factorial(9))

Output:

3.0
362880

Built-in modules

In Python, there are many pre-defined modules available that you can import as needed.

Example:


# Import the math module to utilize mathematical functions
import math
# Compute and display the square root of 9
print(math.sqrt(9))
# Access and print the value of pi from the math module
print(math.pi)
# Convert 3 radians to degrees and print the converted value
print(math.degrees(3))
# Convert 100 degrees to radians and print the converted value
print(math.radians(100))
# Compute and print the sine value for 4 radians
print(math.sin(4))
# Determine and display the cosine value for 90 radians
print(math.cos(90))
# Calculate and print the tangent value for 0.21 radians
print(math.tan(0.21))
# Compute the factorial of 5 (1 * 2 * 3 * 4 * 5) and display the result
print(math.factorial(5))
# Import the random module for generating random numbers
import random
# Generate and print a random integer between 0 and 7 (inclusive)
print(random.randint(0, 7))
# Produce and display a random floating-point number between 0 and 1
print(random.random())
# Create a random floating-point number between 0 and 10 and print it
print(random.random() * 10)
# Define a list containing various data types
List = [1, 3, True, 700, "python", 20, "hello"]
# Select and print a random element from the provided list
print(random.choice(List))
# Import datetime module for managing date and time functionalities
import datetime
from datetime import date
import time
# Get and print the number of seconds elapsed since the Unix Epoch (January 1st, 1970)
print(time.time())
# Convert a specific number of seconds to a date object and display it
print(date.fromtimestamp(454500))

Output:

3.0
3.141592653589793
171.88733853924697
1.7453292519943295
-0.7568024953079282
-0.4480736161291701
0.2131424443826454
120
2
0.422909491178203
7.87090326858619
True
1704256300.043898
1970-01-06

Conclusion

We’ve explored Python modules, including their creation, importation, and other operations. This overview provides insights into Python modules, enabling you to effectively create and utilize them in your Python projects.