You are currently viewing Modules and Packages
Python | Modules and Packages

Modules and Packages

In Python, modules are simply files containing Python definitions, statements, and functions. You can think of a module as a library that can be imported and used in other Python scripts or modules. Python also allows you to group related modules into a package.

Here’s an example of a Python module:


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

def goodbye(name):
    print(f"Goodbye, {name}!")

This module contains two functions: hello() and goodbye(). These functions can be imported and used in other Python scripts.

To use a module in your Python script, you need to import it. Here’s an example of how to import the mymodule module and call its functions:

import mymodule


This will output:

Hello, John!
Goodbye, John!

In addition to importing the entire module, you can also import specific functions or attributes from a module using the from keyword. For example:

from mymodule import hello


This will output:

Hello, Jane!

Packages, on the other hand, are simply directories containing Python modules. A package must contain a special file called, which tells Python that this directory should be treated as a package.

Here’s an example of a Python package:


To import a module from a package, you can use dot notation. For example:

import my_package.module1


This will call the function1() function from the module1 module inside the my_package package.

Leave a Reply