Python Modules: How To Create Modules in Python

Python module refers to the file containing statements and definitions. Any file is a module file if that file contained the Python code and saved as .py extension. In this tutorial we will learn how to create, import, and use Python modules

How to Create a Python Module

Let’s dive into how you can create your own Python module. To start, you simply need to create a new Python file (a file with a `.py` extension). In this file, you can write any Python code, like functions and classes, that you wish to use in other scripts.

For example, let’s create a simple module for performing basic arithmetic operations. We will name it `arithmetic.py`.

# arithmetic.py
def add(x, y):
    return x + y
def subtract(x, y):
    return x - y
def multiply(x, y):
    return x * y
def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        return "Error: Division by zero is undefined"

In this `arithmetic.py` file, we’ve defined four functions: `add()`, `subtract()`, `multiply()`, and `divide()`. This file, when saved in the same directory as your other Python scripts, can now be used as a module.

Importing and Using a Python Module

Once you’ve created a module, you can use the functions and classes it contains in your other Python scripts through importing. The `import` statement in Python is used to load a module into your script’s memory.

Continuing with our arithmetic example, suppose we have another Python script called `main.py`. To use the `add` function from our `arithmetic` module in `main.py`, we’d need to import it like so:

# main.py
import arithmetic
result = arithmetic.add(6, 9)
print(result)  # Outputs: 15

Notice how we’ve used the module name followed by a dot (`.`) and the function name. This is known as dot notation and is a way to access the functions and classes in a module.

If you want to import only a specific function or class from a module, you can use the `from … import …` statement:

# main.py
from arithmetic import add
result = add(6, 9)
print(result)  # Outputs: 15

This way, you don’t need to use the module name before the function name.

In this tutorial you learned how to create, import, and use Python modules
 

#python #python modules #programming

Python Modules: How To Create Modules in Python
4.15 GEEK