PYTHON Tutorial

Modules and Packages

Introduction

Modules and packages are essential tools for organizing and reusing code in Python. A module is a single file containing Python code, while a package is a collection of related modules.

Key Concepts

  • Python import: Used to import a module into the current Python script.
  • Standard library: Collection of pre-built modules included with Python installation.
  • Custom modules: Modules created by the developer.

Practical Steps

To use a module:
  • Import the module using import <module_name>.
  • Access functions, classes, or variables from the module using dot notation (e.g., module_name.function()).
To import modules from the standard library:
  • Use the import <module_name> statement.
  • For example, to import the math module: import math
To import custom modules:
  • Create a Python file with the extension .py (e.g., my_module.py).
  • Save the file in the same directory as the script that needs to import it.
  • Import the module using import <module_name>.
Creating Modules
  • Create a new Python file with the extension .py.
  • Define functions, classes, or variables in the file.
  • Save the file.
To create a package:
  • Create a directory with the package name.
  • Create a special file called __init__.py in the directory.
  • Add modules to the package by saving them in the directory.

Example

Consider the following example where a custom module my_module.py is created:

# my_module.py
def add_numbers(a, b):
    return a + b

In another Python script, we can import and use this module:

import my_module

result = my_module.add_numbers(5, 10)
print(result)  # Output: 15

Conclusion

Modules and packages are powerful tools for organizing and reusing code in Python. By following these practical steps, developers can effectively use, import, and create modules and packages to enhance their Python programs.