Modules in Python

  • Last updated Apr 25, 2024

In Python, a module is a file containing Python code. This file may include function definitions, variables, classes, and executable statements that can be used in an application. Modules allow you to organize your code into separate files, making it easier to manage and reuse code across different programs.

Here's a brief overview of how modules work in Python:

  1. Creating a Module:
  2. To create a module, simply create a Python script (a .py file) that contains your code. For example, if you want to create a module for some utility functions, you can create a file named my_module.py and add some functions as shown in the example below:

    def add(a, b):
        result = a + b
        return result
    
    def substract(a, b):
        result = a - b
        return result
  3. Importing Modules:
  4. To use the functions, classes, or variables defined in a module, you need to import the module into your Python script. This is typically done using the import statement.

    import my_module
    
    x = my_module.add(10, 40)
    y = my_module.substract(10, 5)
    print(x)
    print(y)

    You can also use an alias for the module by importing it with a different name, using the "as" keyword during the import:

    import my_module as md
    
    x = md.add(10, 40)
    y = md.substract(10, 5)
    print(x)
    print(y)
  5. Importing Specific Classes, Variables, and Functions:
  6. If you only need specific functions, classes, or variables from a module, you can import them directly without importing the entire module, using the "from" keyword.

    Example:

    import add, substract from my_module
    
    x = add(10, 40)
    y = substract(10, 5)
    print(x)
    print(y)
  7. Using Variables and Functions:
  8. After a module is imported, you can access its functions, classes, and variables using dot "." notation.

    Example:

    import my_module
    
    variable_value = my_module.my_variable
    result = my_module.my_function()
  9. Standard Library Modules:
  10. Python also comes with a vast standard library of modules that provide various functionalities, such as math, os, datetime, and many more. These can be imported and used in your programs as needed.

    Here's an example of a built-in function in Python, len(), which returns the length of a string, array, tuple, list, or dictionary:

    x = "Hello Buddy"
    y = [11,23,54,74,54]
    
    x_length = len(x)
    y_length = len(y)
    print(x)
    print(y)