Modules and Packages


Imagine modules and packages as neatly arranged toolboxes for your code. They allow you to group related functions, classes, and variables together.

1. Creating a Module:

A module is a separate file that contains code. You can create your own modules to keep your code organized and accessible.

Example: Creating a Module

# Save this in a file named "my_module.py"
def greet(name):
    print("Hello, " + name + "!")

2. Using a Module:

To use code from a module, you import it into your program.

Example: Using a Module

import my_module

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

3. Packages:

A package is a collection of related modules. It helps you create a hierarchical structure for your code.

Example: Creating a Package

# Create a folder named "my_package" and save this in a file named "__init__.py"
# This makes the folder a package

4. Creating Submodules:

Packages can have submodules which are additional modules within the package.

Example: Creating Submodules

# Inside the "my_package" folder, create a file named "submodule.py"
def multiply(a, b):
    return a * b

5. Using Submodules:

You can import submodules just like regular modules.

Example: Using Submodules

from my_package import submodule

result = submodule.multiply(5, 3)
print(result)   # Output: 15

Leave a Reply

Your email address will not be published. Required fields are marked *