What Are Python Modules and Packages? See Examples

Modules and packages in Python help organize and reuse code. A module is a single Python file containing functions, classes, and variables. A package is a collection of modules organized in directories.

Using modules and packages improves code maintainability and scalability.


Why Modules and Packages Are Important

They help to:

  • Reuse code across multiple projects
  • Organize programs logically
  • Avoid code duplication
  • Access built-in and third-party libraries

Example:

import math
print(math.sqrt(16))

Python Modules

A module is simply a .py file with Python code.

Creating a Module

file: greetings.py

def hello():
    print("Hello, Python!")

Using the Module

import greetings
greetings.hello()

Importing Specific Functions

from greetings import hello
hello()

Python Packages

A package is a folder containing multiple modules and an __init__.py file.

my_package/
    __init__.py
    module1.py
    module2.py

Using a Package

from my_package import module1
module1.function_name()

Built-in Modules

Python comes with many built-in modules:

  • math – mathematical operations
  • random – generate random numbers
  • os – interact with operating system
  • sys – system-specific parameters

Example:

import random
print(random.randint(1, 10))

Installing Third-Party Modules

Use pip to install modules:

pip install requests

Best Practices

✔ Use modules for reusable code
✔ Organize related functions into packages
✔ Avoid circular imports
✔ Use meaningful module names


Conclusion

Modules and packages are essential in Python for writing organized, reusable, and maintainable code. They allow developers to work efficiently and structure large projects effectively.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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