argclass

PyPI Version Python Versions Coverage Tests License

Note

For offline access, you can download the full documentation as a PDF: Download PDF Documentation

Declarative CLI parser with type hints, config files, and environment variables.

argclass is a Python library that transforms ordinary Python classes into fully-featured command-line interface parsers. By leveraging Python’s type hints and class syntax, argclass eliminates the boilerplate code typically associated with argument parsing while providing type safety, IDE autocompletion, and seamless integration with configuration files and environment variables.

Key features:

  • Type-safe arguments - Define arguments using Python type hints. argclass automatically validates and converts values to the correct types.

  • Pure OOP design - Unlike decorator-based libraries, argclass uses real classes. This enables proper inheritance and composition for building complex CLIs. Parsers are testable objects you can instantiate, extend, and compose without decorator magic.

  • Zero dependencies - Built entirely on Python’s standard library argparse. No external packages required.

  • IDE support - Full autocompletion and type checking in modern editors like VS Code and PyCharm.

  • Multiple config formats - Load defaults from INI, JSON, or TOML configuration files with automatic type conversion. Each format has built-in support with no additional dependencies (TOML requires Python 3.11+ or tomli package).

  • User-supplied config - config_argument="--config" adds a CLI flag so the end user can point at a config file whose values become argument defaults at invocation time.

  • Environment variables - Read configuration from environment variables with optional prefix support for namespacing.

  • Secret handling - Built-in support for sensitive values that are masked in logs and can be sanitized from the environment.

  • Reusable groups - Define argument groups once and reuse them across multiple parsers for consistent configuration.

  • Subcommands - Build multi-command CLIs like git or docker with nested parser classes.

  • Extensible architecture - Create custom argument types, converters, and configuration file parsers. Integrate with argparse extensions like rich_argparse for enhanced help formatting.

  • argparse compatible - Full compatibility with the standard library argparse. Use any argparse extension or migrate existing code gradually.

import argclass

class Server(argclass.Parser):
    host: str = "127.0.0.1"
    port: int = 8080
    debug: bool = False

if __name__ == "__main__":
    server = Server()
    server.parse_args()
    print(f"Starting server on {server.host}:{server.port}")
$ python server.py --host 0.0.0.0 --port 9000 --debug
Starting server on 0.0.0.0:9000

Why argclass?

argclass bridges the gap between raw argparse (powerful but untyped) and decorator-based frameworks like Click or Typer (ergonomic but dependency-heavy): type-safe, class-based, IDE-friendly, with config files, environment variables, and secret masking built in — and zero dependencies.

See also

The design choices behind that position — classes vs. decorators, the zero-dependency constraint, and a full feature comparison: Why argclass?.

Type-Safe

Define arguments with Python type hints. Get automatic validation and conversion.

Zero Dependencies

Built on stdlib argparse. No external dependencies required.

IDE Support

Full autocompletion and type checking in your editor.

How to Read This Documentation

All code examples in this documentation are automatically tested to ensure they work correctly. This means examples are written in a specific way that may look slightly different from real-world usage.

parse_args() with explicit arguments

Throughout the documentation, you’ll see examples like:

import argclass

class Parser(argclass.Parser):
    host: str = "localhost"
    port: int = 8080

parser = Parser()
parser.parse_args(["--host", "example.com", "--port", "9000"])
assert parser.host == "example.com"

This is for testing purposes only. In real applications, you would call parse_args() without arguments, which reads from sys.argv (the command line):

import argclass

class Parser(argclass.Parser):
    host: str = "localhost"

parser = Parser()
parser.parse_args([])  # In real code: parser.parse_args()
# Real usage reads from command line: python app.py --host example.com

The explicit list form parse_args(["--arg", "value"]) is used in documentation so examples can be tested automatically without requiring actual command-line execution.

Note

Experienced users may pass arguments directly in specific scenarios, such as filtering sys.argv, implementing argument preprocessing, or building nested CLI tools. However, this is not a common pattern for typical applications.

Assert statements

Examples often end with assert statements for verification:

import argclass

class Parser(argclass.Parser):
    name: str

parser = Parser()
parser.parse_args(["--name", "Alice"])
assert parser.name == "Alice"  # Verification for testing

In your actual code, you would simply use the parsed values:

import argclass

class Parser(argclass.Parser):
    name: str = "World"

parser = Parser()
parser.parse_args([])
message = f"Hello, {parser.name}!"
assert message == "Hello, World!"

Environment variables and temporary files

Examples that demonstrate environment variables set them programmatically:

import os
import argclass

os.environ["MY_API_KEY"] = "secret123"  # Set for testing

class Parser(argclass.Parser):
    api_key: str = argclass.Argument(env_var="MY_API_KEY")

parser = Parser()
parser.parse_args([])
assert parser.api_key == "secret123"

del os.environ["MY_API_KEY"]  # Cleanup after test

In production, environment variables would be set externally (by your shell, container orchestrator, or deployment system), not in your Python code.

Similarly, config file examples use NamedTemporaryFile to create test files. In real applications, you would reference actual configuration file paths:

import argclass
from tempfile import NamedTemporaryFile
from pathlib import Path

class Parser(argclass.Parser):
    host: str = "localhost"

# Documentation uses temporary files for testing:
with NamedTemporaryFile(mode="w", suffix=".ini", delete=False) as f:
    f.write("[DEFAULT]\nhost = example.com\n")
    config_path = f.name

parser = Parser(config_files=[config_path])
parser.parse_args([])
assert parser.host == "example.com"

Path(config_path).unlink()

# Real applications use actual paths:
# parser = Parser(config_files=["/etc/myapp.ini", "~/.config/myapp.ini"])

Real-world usage pattern

Here’s what a complete real-world application looks like:

import argclass

class MyApp(argclass.Parser):
    """My application description."""
    host: str = "localhost"
    port: int = 8080
    debug: bool = False

def main():
    app = MyApp()
    app.parse_args([])  # Real code: app.parse_args()
    return f"Starting on {app.host}:{app.port}"

result = main()
assert "localhost:8080" in result

Run it with: python myapp.py --host 0.0.0.0 --port 9000 --debug

Installation

argclass requires Python 3.10 or later and has no external dependencies.

Using pip

The simplest way to install argclass:

pip install argclass

Using uv

For faster installation with uv:

uv add argclass

Or in a virtual environment:

uv pip install argclass

Using Poetry

Add argclass to your Poetry project:

poetry add argclass

From Source

Clone the repository and install in development mode:

git clone https://github.com/mosquito/argclass.git
cd argclass
pip install -e .

Verifying Installation

After installation, verify it works:

$ python -m argclass --help

This launches an interactive demo with subcommands that demonstrate each argclass feature. Every subcommand prints its own source code, so you can see both the code and the result:

$ python -m argclass basic --name World --count 3 --debug
$ python -m argclass types --mode fast --tags a b c --color green
$ python -m argclass groups --server-host 0.0.0.0 --db-port 3306
$ python -m argclass secrets --api-key my-secret
$ DEMO_HOST=example.com python -m argclass env
$ python -m argclass subcommands hello --user Alice

Quick Examples

Groups

Organize related arguments into reusable groups. Group arguments are automatically prefixed with the group name. Groups can also be nested inside other groups for arbitrary depth — names join with - (CLI), _ (env vars), or . (INI/TOML sections):

import argclass

class DatabaseGroup(argclass.Group):
    host: str = "localhost"
    port: int = 5432

class Parser(argclass.Parser):
    debug: bool = False
    db = DatabaseGroup()

parser = Parser()
parser.parse_args(["--db-host", "prod.db", "--db-port", "5432"])
assert parser.db.host == "prod.db"

Config Files

Load defaults from INI, JSON, or TOML configuration files. Values from config files can be overridden by environment variables or CLI arguments:

import argclass

class Parser(argclass.Parser):
    host: str = "localhost"
    port: int = 8080

parser = Parser(config_files=[
    "/etc/myapp.ini",
    "~/.config/myapp.ini",
])

# Reads from config files in order, then environment, then CLI

Environment Variables

Read configuration from environment variables. Use auto_env_var_prefix to automatically generate environment variable names from argument names:

import argclass

class Parser(argclass.Parser):
    host: str = "localhost"
    port: int = 8080

parser = Parser(auto_env_var_prefix="MYAPP_")
# Reads from MYAPP_HOST, MYAPP_PORT

Get Started

New to argclass? Here’s the recommended learning path:

Quick Start (5 minutes)

The Quick Start guide covers the essentials:

  • Defining arguments with type hints

  • Required vs optional arguments

  • Boolean flags and short aliases

  • Reading from environment variables

  • Basic help text customization

This is enough to build simple CLI tools and understand argclass fundamentals.

Tutorial (30 minutes)

The Tutorial walks through building a complete backup tool:

  • Starting with a basic parser structure

  • Adding options with defaults and help text

  • Organizing arguments into groups

  • Creating subcommands for different operations

  • Loading configuration from files

  • Reading secrets from environment variables

By the end, you’ll understand how all argclass features work together.

How-to Guides

Once comfortable with the basics, explore the How-to Guides for detailed coverage:

Reference

For exact facts, look these up rather than read them through:

Concepts

To understand why argclass works the way it does — the mental models behind the API — see the Explanation section: the parser/group model, the configuration model, the type system, and the security model.

Quick Start

5 minute introduction

Learn the basics: arguments, types, flags, and environment variables.

Quick Start
Tutorial

Complete walkthrough

Build a real CLI application step by step.

Tutorial

Documentation

The documentation follows the four Diátaxis modes — Tutorials to learn by doing, How-to Guides for specific tasks, Reference for exact facts, and Explanation to understand the design.

How-to Guides

Indices and tables