Monday, 24 February 2025

Modules in Python

Unit 3 - 3.2 Modules in Python

Modules in Python: A Detailed Overview

In Python, a module is a file containing Python code that defines functions, classes, and variables, making it reusable across different programs. Modules help in organizing code logically and efficiently.


1. Types of Modules in Python

Python modules can be classified into three main types:

  1. Built-in Modules – Pre-installed modules that come with Python (e.g., math, sys, os).
  2. User-defined Modules – Custom modules created by users to organize their code.
  3. Third-party Modules – External modules installed via pip (e.g., numpy, pandas).

2. Creating and Using a Module

A module in Python is simply a .py file containing functions, classes, and variables.

To create a Python module, write the desired code and save that in a file with .py extension. Let’s understand it better with an example:

Creating a Simple Module

Let's create a module named mymodule.py:


# mymodule.py def add(a, b): return a + b def subtract(a, b): return a - b

Importing a Module

To use mymodule.py in another Python script, you can import it using the import statement:


import mymodule result = mymodule.add(5, 3) print(result) # Output: 8

Using from Keyword

You can import specific functions from a module:


from mymodule import add print(add(10, 4)) # Output: 14

Using as Keyword for Aliasing

You can rename a module while importing:


import mymodule as mm print(mm.subtract(10, 5)) # Output: 5

3. Built-in Modules in Python

Python has several built-in modules. Here are a few common ones:

a) math Module – Provides mathematical functions.


import math print(math.sqrt(16)) # Output: 4.0 print(math.factorial(5)) # Output: 120

b) random Module – Used for generating random numbers.


import random print(random.randint(1, 100)) # Output: Random number between 1 and 100

c) datetime Module – Handles date and time.

import datetime current_time = datetime.datetime.now() print(current_time)

d) os Module – Interacts with the operating system.


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

4. Installing and Using Third-party Modules

Python allows installation of external modules via pip (Python's package manager).

Installing a Module


pip install numpy

Using the Installed Module


import numpy as np arr = np.array([1, 2, 3]) print(arr) # Output: [1 2 3]

5. Special Module Attributes

Python provides special attributes for modules:


# Inside mymodule.py print(__name__) # Outputs '__main__' if run directly, or 'mymodule' if imported

Checking if a Module is Run Directly


if __name__ == "__main__": print("This script is being run directly")

6. Finding and Listing Module Functions

You can use the dir() function to list all available functions in a module:


import math print(dir(math)) # Lists all functions in math module

7. Python Packages (Modules Inside Folders)

A package is a collection of modules stored in a directory containing an __init__.py file.

Creating a Package


mypackage/ │── __init__.py │── module1.py │── module2.py

Using a Package


from mypackage import module1 module1.some_function()

Conclusion

  • Modules help in reusability and better organization of Python code.
  • Built-in modules provide essential functionalities.
  • User-defined modules can be created for custom functions.
  • Third-party modules can be installed via pip for additional features.
  • Packages organize multiple modules into structured directories.

No comments:

Post a Comment

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...