5.5 Importing Modules and Standard Library in Python

Python comes with a rich standard library that includes modules for handling tasks like file I/O, math operations, working with dates and times, and more. You can also write your own modules or install third-party modules using tools like pip. To use these modules in your programs, you need to import them.

In this section, we’ll explore how to import modules, use specific functions from them, and understand different ways to import parts of the Python standard library.


5.5.1 What is a Module?

A module is a file containing Python definitions, functions, and variables that you can reuse in other Python programs. A module can contain anything from simple variables and functions to more complex classes and data structures.

  • Standard library modules: Pre-built modules provided by Python (e.g., math, datetime).
  • User-defined modules: Custom modules you create by saving Python code in a .py file.
  • Third-party modules: Modules installed from external sources like PyPI (Python Package Index).

5.5.2 Basic Import Syntax

You can import a module using the import keyword followed by the module’s name. Once imported, you can access functions, variables, and classes from that module using dot notation (module_name.function_name()).

Example:

import math

result = math.sqrt(16)
print(result)  # Output: 4.0

In this example:

  • We import the math module using import math.
  • The sqrt() function is accessed as math.sqrt() and calculates the square root of 16.

5.5.3 Importing Specific Functions or Variables

If you only need specific functions or variables from a module, you can use the from ... import syntax. This allows you to import only what you need without importing the entire module.

Example:

from math import sqrt, pi

print(sqrt(25))  # Output: 5.0
print(pi)        # Output: 3.141592653589793

In this example:

  • Only the sqrt() function and pi constant are imported from the math module.
  • You can call these directly without prefixing them with math..

5.5.4 Importing with Aliases

To simplify usage or avoid conflicts, you can import a module or function with an alias using the as keyword. This is useful when the module name is long or if there is a naming conflict with another function or variable.

Example: Alias for a Module:

import numpy as np

array = np.array([1, 2, 3, 4])
print(array)  # Output: [1 2 3 4]

Here, the numpy module is imported with the alias np. This makes it easier and quicker to reference the module when working with large codebases.

Example: Alias for a Function:

from math import factorial as fact

print(fact(5))  # Output: 120

In this case, the factorial() function from the math module is imported with the alias fact, making it easier to call.


5.5.5 Importing Everything from a Module

If you want to import everything from a module, you can use the from ... import * syntax. However, this is generally discouraged because it can clutter the namespace and lead to naming conflicts.

Example:

from math import *

print(sqrt(36))  # Output: 6.0
print(factorial(5))  # Output: 120

Here, all functions and variables from the math module are imported. You can call them without the math. prefix.

Caution: Avoid using from ... import * in large programs to prevent name collisions and make it clear where each function or variable comes from.


5.5.6 Checking Available Functions and Variables in a Module

You can use the dir() function to list all the functions, variables, and attributes defined in a module.

Example:

import math

print(dir(math))

This will print a list of all available functions and variables in the math module.


5.5.7 Working with the Python Standard Library

Python's standard library includes many useful modules that can handle various common tasks. Let’s look at some popular modules from the standard library.

5.5.7.1 The math Module

The math module provides mathematical functions like trigonometry, logarithms, and more.

Example:

import math

print(math.pi)         # Output: 3.141592653589793
print(math.sqrt(64))   # Output: 8.0
print(math.factorial(5))  # Output: 120

5.5.7.2 The datetime Module

The datetime module allows you to work with dates, times, and timestamps.

Example:

import datetime

current_time = datetime.datetime.now()
print(current_time)  # Output: Current date and time

You can use datetime for a wide variety of date and time manipulations, including formatting dates, adding time deltas, and more.


5.5.7.3 The random Module

The random module is used to generate random numbers, shuffle lists, and perform random sampling.

Example:

import random

random_number = random.randint(1, 100)
print(random_number)  # Output: A random number between 1 and 100

random_choice = random.choice(['apple', 'banana', 'cherry'])
print(random_choice)  # Output: Randomly selected fruit

5.5.7.4 The os Module

The os module provides functions for interacting with the operating system, such as reading environment variables, working with file paths, and managing directories.

Example:

import os

current_directory = os.getcwd()
print(current_directory)  # Output: Current working directory

You can also use os to list files in a directory, create directories, or remove files.


5.5.8 Creating Your Own Module

You can create your own Python module by simply writing Python code in a .py file. This allows you to reuse code across different programs by importing it as a module.

Steps:

  1. Create a new Python file, say mymodule.py, with the following content:
# mymodule.py

def greet(name):
    return f"Hello, {name}!"
  1. In your main Python program, you can import and use this module:
import mymodule

print(mymodule.greet("Alice"))  # Output: Hello, Alice!

5.5.9 Installing and Importing Third-Party Modules

You can use the Python package manager pip to install third-party modules from the Python Package Index (PyPI). Once installed, these modules can be imported just like standard library or user-defined modules.

Installing a Module with pip:

To install a third-party module (e.g., requests), use the following command in your terminal or command prompt:

pip install requests

Using a Third-Party Module:

Once installed, you can import and use the module:

import requests

response = requests.get("https://api.github.com")
print(response.status_code)  # Output: 200

In this example, we use the requests module to make an HTTP request to GitHub’s API.


5.5.10 Summary

  • Modules are files containing Python code (functions, variables, and classes) that can be imported and reused in other Python programs.
  • You can import entire modules using import module_name or import specific functions and variables using from module_name import function_name.
  • Use aliases with the as keyword to simplify long module or function names.
  • The standard library includes many built-in modules for tasks such as math, date/time handling, randomization, and file manipulation.
  • You can create custom modules by saving Python code in a .py file and importing it into other programs.
  • Use pip to install and import third-party modules from the Python Package Index (PyPI).

Mastering how to import and use modules will significantly enhance your ability to write modular, reusable, and efficient Python code by leveraging both the Python standard library and third-party packages.