☼
⌃
☰

Python Modules and Packages

Table of Contents

Python Modules and Packages

Organize code into reusable components.

Examples

Module Example

Let's say you have a file named my_module.py with the following content:

PYTHON
# my_module.py
def greet(name):
    return f"Hello, {name}!"

def farewell(name):
    return f"Goodbye, {name}!"

You can then use this module in another Python script:

PYTHON
# main.py
import my_module

print(my_module.greet("Gregory"))
print(my_module.farewell("Gregory"))

Package Example

Consider the following directory structure for a package named my_package:

my_package/
├── __init__.py
├── module_a.py
└── sub_package/
    ├── __init__.py
    └── module_b.py

my_package/__init__.py (can be empty or define package-level imports):

PYTHON
# my_package/__init__.py
# You could import specific functions here to make them directly accessible
# from my_package. For example:
# from .module_a import function_from_a

my_package/module_a.py:

PYTHON
# my_package/module_a.py
def function_from_a():
    return "This is from module A"

my_package/sub_package/__init__.py (can be empty):

PYTHON
# my_package/sub_package/__init__.py

my_package/sub_package/module_b.py:

PYTHON
# my_package/sub_package/module_b.py
def function_from_b():
    return "This is from module B in a sub-package"

You can then use this package in another Python script:

PYTHON
# main.py
import my_package.module_a
from my_package.sub_package import module_b

print(my_package.module_a.function_from_a())
print(module_b.function_from_b())