techmore.in

Python - Modules

What are Python Modules?

A module in Python is a file containing Python definitions and statements. Modules allow you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use.

Why Use Modules?

  • Code Reusability
  • Maintainability
  • Namespace Separation
  • Cleaner project structure

How to Create and Import Modules

python
# mymodule.py
def greet(name):
    return f"Hello, {name}!"

python
# main.py
import mymodule

print(mymodule.greet("Alice"))

Types of Modules

  • Built-in Modules: Already installed with Python (e.g., math, os, sys).
  • User-defined Modules: Custom modules created by the user.
  • Third-party Modules: External libraries installed using tools like pip (e.g., numpy, requests).

Example: Using a Built-in Module

python
import math

print(math.sqrt(16))  # Output: 4.0

Import Variations

  • import module
  • from module import function
  • import module as alias
  • from module import *

Best Practices

  • Use descriptive names for modules
  • Avoid wildcard imports
  • Group imports: standard, third-party, and local

Conclusion

Modules are a foundational concept in Python that encourage code reuse, readability, and modular design. By effectively using built-in, user-defined, and third-party modules, you can build scalable and maintainable Python applications.