Modules

Modules in Python are files containing Python code that can be reused in other programs. They help in organizing code and promoting code reusability by allowing you to import functions, classes, and variables from one Python file into another. This tutorial provides an overview of Python modules, including their creation, usage, and benefits.

Creating a Module

A Python module is simply a Python file with the .py extension. You can create a module by writing functions, classes, or variables in a Python file and saving it with a meaningful name.


      # my_module.py

      def greet(name):
          return f"Hello, {name}!"
      

Importing a Module

To use functions or other items from a module in your Python program, you need to import the module. There are various ways to import modules:

Importing the Entire Module


      import my_module

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

Importing Specific Items from a Module

You can also import specific items (functions, classes, or variables) from a module.


      from my_module import greet

      result = greet("Bob")
      print(result)  # Output: Hello, Bob!
      

Renaming a Module

You can use the as keyword to rename a module during import.


      import my_module as mm

      result = mm.greet("Eve")
      print(result)  # Output: Hello, Eve!
      

Standard Library Modules

Python comes with a standard library that includes many pre-built modules, providing a wide range of functionalities. These modules cover tasks like math operations, file handling, date and time manipulation, and much more.


      import math

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

Third-Party Modules

Apart from the standard library, Python offers an extensive collection of third-party modules that can be installed using package managers like pip. These modules extend Python's capabilities and allow you to accomplish complex tasks efficiently.


      # Installing a third-party module using pip
      # pip install requests

      import requests

      response = requests.get("https://www.example.com")
      print(response.status_code)  # Output: 200