Using modules, we can modularize the larger codebase into smaller parts which promotes code reusability, and maintainability. While Python provides a rich set of built-in modules, we often need to create our own custom modules to hide some specific functionalities. In this article, we will see how to create a module and import our own modules in Python.

Let’s first create the sample Python module with the following content and name it my_module.py and save it in the same directory where the main Python script is present.

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

def add(a, b):
    return a + b

In the main Python script, import the above module using the import as shown below.

import my_module

my_module.greet("Alice")
result = my_module.add(3, 5)
print(result)

In the above example, we import the my_module and by prefixing the module name we can use the greet() and add() functions.

Import specific functions

We can also import the specific functions from my_module instead of importing all the functions by using the from keyword.

from my_module import greet, add

greet("Bob")
result = add(2, 4)
print(result)

    Categorized in:

    Tagged in: