PYTHON

Python Module: Creating and Importing Modules in Python

Modules in Python are files with functions, classes, and variables that you can import and use in different programs. Additionally, some modules provide useful constants or configuration settings.

How to Use Python Modules

Python Importing a Module

You can import a module using the import statement with the module’s name. By importing a module, you can use its functions, classes, and variables within your current Python script.

import module_name

Using the from keyword, you can also import specific functions or classes from a module. This way, you can avoid loading the entire module and improve performance.

from module_name import function_name, ClassName

Python Creating a Module

You can create your own modules by saving Python code in a .py file. Creating a module is useful for organizing your code into components you can import into other scripts.

# greetings.py
def say_hello(name):
    return f"Hello, {name}!"

You can then import and use this module in another Python script. This modular approach enhances code readability and maintainability.

# main.py
import greetings
print(greetings.say_hello('Alice'))  # Outputs: 'Hello, Alice!'

Python Using Modules

Once imported, you can use the functions, classes, and variables from the module. This allows you to build upon existing code and reduce redundancy.

import greetings
message = greetings.say_hello('Bob')
print(message)  # Outputs: 'Hello, Bob!'

Basic Usage

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

from math import pi
print(pi)  # Outputs: 3.141592653589793

When to Use Python Modules

Modules are great for breaking your programs into self-contained units or leveraging functionality from existing modules.

Reusing Code

Modules let you reuse code in multiple programs, reducing duplication. Changes to the module automatically update in all scripts that import it.

# module: math_operations.py
def add(a, b):
    return a + b

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

# main.py
import math_operations
print(math_operations.add(10, 5))  # Outputs: 15
print(math_operations.subtract(10, 5))  # Outputs: 5

Organizing Code

Modules help organize large codebases by splitting them into smaller, manageable pieces. This improves readability and helps you keep your project structured, making it easier to navigate and understand.

Leveraging Built-in Functionality

Python provides many built-in modules like math, os, and random that offer a wealth of functionality. These modules can save you effort by providing reliable solutions for common programming tasks.

import random
random_number = random.randint(1, 10)
print(random_number)  # Outputs a random number between 1 and 10

Examples of Using Python Modules

Web Development

Web development frameworks like Django or Flask utilize modules extensively. You can create modules for different parts of your web application, such as user authentication, database models, and views.

# user_auth.py
def authenticate_user(username, password):
    # Simplified authentication logic
    return username == "admin" and password == "admin123"

# main.py
import user_auth
is_authenticated = user_auth.authenticate_user("admin", "admin123")
print(is_authenticated)  # Outputs: True

Data Science

Data science projects often use modules like pandas and numpy for data manipulation and computation. You can create custom modules to preprocess data, perform specific analyses, or generate reports.

# data_processing.py
import pandas as pd

def load_data(file_path):
    return pd.read_csv(file_path)

# main.py
import data_processing
data = data_processing.load_data("data.csv")
print(data.head())

Machine Learning

Machine learning workflows benefit from modular code to separate data preprocessing, model training, and evaluation. Libraries like scikit-learn and tensorflow are popular alongside custom modules.

# ml_model.py
from sklearn.linear_model import LinearRegression

def train_model(X, y):
    model = LinearRegression()
    model.fit(X, y)
    return model

# main.py
import ml_model
X = [[1], [2], [3], [4]]
y = [1, 2, 3, 4]
model = ml_model.train_model(X, y)
print(model.coef_)

Learn More About Python Modules

Python Installing Modules

You can install Python modules in your command line using pip, the package installer for Python. To install a module, use pip install with the name of the module. This command downloads the module from the Python Package Index (PyPI) and installs it in your environment.

pip install module_name

Python Listing Installed Modules

You can use the pip command to list all installed Python modules. pip list shows all modules installed in your environment, which helps you manage dependencies and ensure compatibility.

pip list

Module Not Found Error in Python

A "module not found" error occurs when Python can't find the module you're trying to import. This usually means the module isn't installed in your environment. To resolve this, you can try to install the missing module using pip.

pip install module_name

If you run into issues installing a module with pip, ensure that you’re using the correct module name. Also, make sure that the module available in the Python Package Index (PyPI).

Python Math Module

The math module is a popular Python mathematical module. math provides common functions such as trigonometric functions, logarithms, and constants like pi. Scientific and engineering applications often use functionality from the math module.

import math
circle_area = math.pi * (5 ** 2)
print(circle_area)  # Outputs the area of a circle with a radius of 5

Python OS Module

The os module allows interaction with the operating system. You can read or write files and manipulate the file system. This is essential for automating tasks and managing files from within a script.

import os
current_directory = os.getcwd()
print(current_directory)  # Outputs the current working directory

Python Random Module

The random module generates random numbers. This can be useful for simulations, games, and random selection tasks. The module provides functions to generate random values, shuffle sequences, and more.

import random
random_list = random.sample(range(1, 100), 10)
print(random_list)  # Outputs a list of 10 random numbers between 1 and 99

Python Requests Module

The requests module makes it easy to send HTTP requests. requests is popular for web scraping and API interactions, making it a powerful tool for integrating with web services.

import requests
response = requests.get('<https://api.example.com/data>')
print(response.json())  # Outputs JSON data from the response

Python Time Module

The time module provides time-related functions. You can access the current time, pause execution, or measure elapsed time. This is useful for performance testing and scheduling tasks.

import time
current_time = time.time()
print(current_time)  # Outputs the current time in seconds since the epoch

Python Logging Module

The logging module helps you track events in your code. It's essential for debugging and monitoring applications, providing a way to record errors, warnings, and informational messages.

import logging
logging.basicConfig(level=logging.INFO)
logging.info('This is an info message')

Python Regex Module

The re module allows you to work with regular expressions. This is useful for string matching and manipulation, enabling complex search and replace operations.

import re
pattern = re.compile(r'\\d+')
matches = pattern.findall('There are 123 apples and 456 oranges')
print(matches)  # Outputs: ['123', '456']

Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH