Claude Code for optparse: Python Legacy Option Parser — Claude Skills 360 Blog
Blog / AI / Claude Code for optparse: Python Legacy Option Parser
AI

Claude Code for optparse: Python Legacy Option Parser

Published: December 23, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s optparse module parses --flag and -f style options — it is the predecessor to argparse and is still found in older codebases. import optparse. Create: parser = optparse.OptionParser(usage="%prog [options] arg", description="..."). Add option: parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="enable verbose output"). Parse: (options, args) = parser.parse_args()options is a Values namespace; args is the list of non-option arguments. Actions: store (default), store_true, store_false, store_const, append, count, callback. Types: "string" (default), "int", "float", "long", "complex", "choice". Groups: grp = optparse.OptionGroup(parser, "Advanced") + grp.add_option(...) + parser.add_option_group(grp). Defaults: parser.set_defaults(output="out.txt"). Error: parser.error("message") prints to stderr and exits 2. Help: parser.format_help(). Note: optparse is deprecated since Python 3.2 — prefer argparse for new code. Claude Code generates maintenance scripts, legacy CLI tools, migration helpers, and backward-compatible option parsers.

CLAUDE.md for optparse

## optparse Stack
- Stdlib: import optparse
- Create: parser = optparse.OptionParser(usage="%prog [opts] arg")
- Add:    parser.add_option("-v","--verbose", action="store_true", default=False)
- Parse:  opts, args = parser.parse_args()   # opts.verbose, args[0]
- Error:  parser.error("bad input")          # exit 2
- Help:   parser.format_help()
- Note:   DEPRECATED since Python 3.2 — use argparse for new code

optparse CLI Pipeline

# app/optparseutil.py — builder, validator, help, migrator, legacy runner
from __future__ import annotations

import optparse
import os
import sys
from dataclasses import dataclass, field
from typing import Any


# ─────────────────────────────────────────────────────────────────────────────
# 1. Builder helper
# ─────────────────────────────────────────────────────────────────────────────

def make_parser(
    usage: str = "%prog [options]",
    description: str = "",
    epilog: str = "",
    version: "str | None" = None,
) -> optparse.OptionParser:
    """
    Create a configured OptionParser with standard defaults.

    Example:
        parser = make_parser(
            usage="%prog [options] FILE",
            description="Process a file.",
            version="1.0",
        )
        parser.add_option("-v", "--verbose", action="store_true", default=False)
        opts, args = parser.parse_args()
    """
    kwargs: dict[str, Any] = dict(
        usage=usage,
        description=description,
        epilog=epilog,
    )
    if version:
        kwargs["version"] = version
    return optparse.OptionParser(**kwargs)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Typed option factories
# ─────────────────────────────────────────────────────────────────────────────

def add_flag(
    parser: optparse.OptionParser,
    short: str,
    long: str,
    dest: "str | None" = None,
    default: bool = False,
    help: str = "",
) -> None:
    """
    Add a boolean flag (--flag / --no-flag pattern).

    Example:
        add_flag(parser, "-v", "--verbose", help="print extra output")
        add_flag(parser, "-q", "--quiet",   help="suppress output", default=False)
    """
    parser.add_option(
        short, long,
        action="store_true",
        dest=dest or long.lstrip("-").replace("-", "_"),
        default=default,
        help=help,
    )


def add_string_option(
    parser: optparse.OptionParser,
    short: str,
    long: str,
    default: "str | None" = None,
    metavar: str = "VALUE",
    help: str = "",
) -> None:
    """
    Add a string-valued option.

    Example:
        add_string_option(parser, "-o", "--output", default="out.txt",
                          metavar="FILE", help="output file path")
    """
    parser.add_option(
        short, long,
        type="string",
        default=default,
        metavar=metavar,
        help=help,
    )


def add_int_option(
    parser: optparse.OptionParser,
    short: str,
    long: str,
    default: int = 0,
    metavar: str = "N",
    help: str = "",
) -> None:
    """
    Add an integer option.

    Example:
        add_int_option(parser, "-n", "--count", default=10, help="repeat count")
    """
    parser.add_option(
        short, long,
        type="int",
        default=default,
        metavar=metavar,
        help=help,
    )


def add_choice_option(
    parser: optparse.OptionParser,
    short: str,
    long: str,
    choices: list[str],
    default: "str | None" = None,
    help: str = "",
) -> None:
    """
    Add an option restricted to a predefined set of choices.

    Example:
        add_choice_option(parser, "-l", "--level",
                          choices=["debug","info","warn","error"],
                          default="info", help="log level")
    """
    parser.add_option(
        short, long,
        type="choice",
        choices=choices,
        default=default,
        help=help + f" (choices: {', '.join(choices)})",
    )


def add_append_option(
    parser: optparse.OptionParser,
    short: str,
    long: str,
    metavar: str = "VALUE",
    help: str = "",
) -> None:
    """
    Add an option that can be specified multiple times (appends to a list).

    Example:
        add_append_option(parser, "-i", "--include", metavar="PATTERN",
                          help="include pattern (can repeat)")
        # --include "*.py" --include "*.md"  → opts.include = ["*.py","*.md"]
    """
    parser.add_option(
        short, long,
        action="append",
        metavar=metavar,
        help=help,
    )


# ─────────────────────────────────────────────────────────────────────────────
# 3. Parsed options validator
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class ParsedCLI:
    """
    Structured wrapper around optparse.parse_args() output.

    Example:
        cli = ParsedCLI.from_parser(parser)
        if not cli.ok:
            print(cli.errors)
        else:
            print(cli.opts.output, cli.args)
    """
    opts:   optparse.Values
    args:   list[str]
    errors: list[str] = field(default_factory=list)

    @classmethod
    def from_argv(
        cls,
        parser: optparse.OptionParser,
        argv: "list[str] | None" = None,
    ) -> "ParsedCLI":
        try:
            opts, args = parser.parse_args(argv)
            return cls(opts=opts, args=args)
        except SystemExit:
            return cls(opts=optparse.Values(), args=[], errors=["parse failed"])

    @property
    def ok(self) -> bool:
        return not self.errors

    def require_args(
        self,
        parser: optparse.OptionParser,
        min_args: int,
        max_args: "int | None" = None,
    ) -> "ParsedCLI":
        """Validate positional argument count in-place."""
        n = len(self.args)
        if n < min_args:
            self.errors.append(f"expected at least {min_args} argument(s), got {n}")
            parser.print_help()
        if max_args is not None and n > max_args:
            self.errors.append(f"expected at most {max_args} argument(s), got {n}")
        return self

    def require_file(self, path_attr: str) -> "ParsedCLI":
        """Validate that the option named path_attr points to an existing file."""
        p = getattr(self.opts, path_attr, None)
        if p and not os.path.isfile(p):
            self.errors.append(f"file not found: {p!r}")
        return self


# ─────────────────────────────────────────────────────────────────────────────
# 4. argparse migration helper
# ─────────────────────────────────────────────────────────────────────────────

def opts_to_dict(opts: optparse.Values) -> dict[str, Any]:
    """
    Convert an optparse Values namespace to a plain dict.
    Useful when migrating to argparse or passing to libraries expecting dicts.

    Example:
        d = opts_to_dict(opts)
        print(d)
    """
    return vars(opts)


def describe_parser(parser: optparse.OptionParser) -> list[dict]:
    """
    Describe all registered options as a list of dicts.
    Useful for generating argparse equivalents.

    Example:
        for opt_info in describe_parser(parser):
            print(opt_info)
    """
    result = []
    for opt in parser.option_list:
        if opt.dest is None:
            continue
        result.append({
            "opts":    opt._short_opts + opt._long_opts,
            "dest":    opt.dest,
            "action":  opt.action,
            "type":    opt.type,
            "default": opt.default,
            "help":    opt.help,
        })
    return result


# ─────────────────────────────────────────────────────────────────────────────
# 5. Complete CLI application example
# ─────────────────────────────────────────────────────────────────────────────

def build_demo_parser() -> optparse.OptionParser:
    """
    Build a representative demo OptionParser for testing.

    Example:
        parser = build_demo_parser()
        opts, args = parser.parse_args(["--verbose", "input.txt"])
    """
    parser = make_parser(
        usage="%prog [options] INPUT",
        description="Demo optparse CLI.",
        version="1.0",
    )

    # Core options
    add_flag(parser, "-v", "--verbose", help="verbose output")
    add_flag(parser, "-d", "--dry-run", help="dry run — no writes")
    add_string_option(parser, "-o", "--output", default="-",
                      metavar="FILE", help="output file (default: stdout)")
    add_int_option(parser, "-n", "--count", default=10,
                   help="max items to process")
    add_choice_option(parser, "-f", "--format",
                      choices=["text", "json", "csv"],
                      default="text", help="output format")

    # Advanced group
    grp = optparse.OptionGroup(parser, "Advanced",
                               "Options for power users.")
    grp.add_option("--timeout", type="int", default=30,
                   help="timeout in seconds (default: 30)")
    grp.add_option("--retries", type="int", default=3,
                   help="retry count (default: 3)")
    add_append_option(grp, "-e", "--exclude",
                      metavar="PATTERN", help="exclude pattern (repeatable)")
    parser.add_option_group(grp)

    return parser


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== optparse demo ===")

    parser = build_demo_parser()

    # ── print_help ────────────────────────────────────────────────────────────
    print("\n--- format_help ---")
    print(parser.format_help())

    # ── parse simple argv ─────────────────────────────────────────────────────
    print("\n--- parse_args ---")
    opts, args = parser.parse_args(
        ["-v", "-n", "5", "--format", "json", "--exclude", "*.log",
         "--exclude", "*.tmp", "myfile.txt"]
    )
    print(f"  verbose  = {opts.verbose}")
    print(f"  count    = {opts.count}")
    print(f"  format   = {opts.format}")
    print(f"  output   = {opts.output}")
    print(f"  exclude  = {opts.exclude}")
    print(f"  timeout  = {opts.timeout}")
    print(f"  args     = {args}")

    # ── opts_to_dict ──────────────────────────────────────────────────────────
    print("\n--- opts_to_dict ---")
    d = opts_to_dict(opts)
    for k, v in sorted(d.items()):
        print(f"  {k}: {v!r}")

    # ── describe_parser ───────────────────────────────────────────────────────
    print("\n--- describe_parser ---")
    for opt_info in describe_parser(parser):
        print(f"  {opt_info['opts']}  dest={opt_info['dest']!r}  "
              f"type={opt_info['type']}  default={opt_info['default']!r}")

    # ── ParsedCLI.from_argv ────────────────────────────────────────────────────
    print("\n--- ParsedCLI.from_argv ---")
    cli = ParsedCLI.from_argv(parser, ["--count", "3", "in.txt"])
    cli.require_args(parser, min_args=1)
    print(f"  ok={cli.ok}  count={cli.opts.count}  args={cli.args}")

    print("\n=== done ===")

For the argparse alternative — argparse is optparse’s official successor (Python 3.2+), adding subcommands, mutually exclusive groups, file type, nargs, */+ quantifiers, and better error messages — always use argparse for new code; use optparse only when maintaining existing scripts that depend on it or when migrating old code incrementally. For the click (PyPI) / typer (PyPI) alternative — click and typer (built on click) provide decorator-based CLI building with automatic type coercion, nested command groups, environment variable integration, and rich testing utilities — use these for new user-facing CLI tools where developer ergonomics matter; use optparse/argparse when you need zero dependencies or are working inside an environment where pip is unavailable. The Claude Skills 360 bundle includes optparse skill sets covering make_parser() factory, add_flag()/add_string_option()/add_int_option()/add_choice_option()/add_append_option() typed option factories, ParsedCLI.from_argv() with require_args()/require_file() validators, opts_to_dict() conversion, describe_parser() introspection, and build_demo_parser() with grouped options. Start with the free tier to try option parsing patterns and optparse pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free