Python Modules, Main Function and Argparse

📑 Navigation

What is a Module? • Importing from Subdirectories • The Main Function • The if name == "main" Pattern • Module vs Client • Public and Private Attributes • Python Libraries • Documentation • Command-Line Arguments with Argparse • Key Takeaways

What is a Module?

Definition

A module is a Python file (.py file) containing Python definitions, functions, and statements that can be imported and used in other Python scripts.

Purpose: Modules help organize code into reusable, maintainable components.

Why Use Modules?

✅ Code Reusability: Write once, use many times

✅ Organization: Separate concerns into different files

✅ Maintainability: Easier to update and debug

✅ Namespace Management: Avoid naming conflicts

✅ Collaboration: Team members can work on different modules

Basic Import

# my_[module.py](<http://module.py>)
def greet(name):
    return f"Hello, {name}!"

PI = 3.14159
# [main.py](<http://main.py>)
import my_module

print(my_module.greet("Harry"))  # Output: Hello, Harry!
print(my_module.PI)               # Output: 3.14159

Import Specific Functions

from my_module import greet, PI

print(greet("Harry"))  # No need for my_module. prefix
print(PI)

Import with Alias

import my_module as mm

print(mm.greet("Harry"))