Skip to content

optparse: parsing many positional arguments takes quadratic time #161282

Open

Description

@thejesh23

Bug report

Bug description:

OptionParser.parse_args() is quadratic in the number of positional arguments: _process_args() removes each one from the front of rargs with del rargs[0].

cpython/Lib/optparse.py

Lines 1420 to 1422 in 7e3290d

elif self.allow_interspersed_args:
largs.append(arg)
del rargs[0]

import optparse, time

parser = optparse.OptionParser()
parser.add_option('-v', action='store_true')
args = ['-v'] + [f'file{i}' for i in range(200_000)]
start = time.perf_counter()
parser.parse_args(args)
print(f'{time.perf_counter() - start:.3f} s')  # 2.445 s on main, 0.009 s with the fix

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    on Nov 4, 2026
  2. added
    AI-needs-explanation
    on Nov 4, 2026
  3. bedevere-app commented on Nov 4, 2026

    @bedevere-app

    Thank you for taking the time to open this issue. Python is a community-driven project, and we want it to be a welcoming place to learn and collaborate.

    This issue appears to have been written with AI assistance. Please explain your issue in your own words and describe how you checked the information you provided. This helps us understand your issue and leaves more time to address other issues.

    Please read our guidelines for using AI tools.

  4. thejesh23 commented on Nov 4, 2026

    @thejesh23
    ContributorAuthor

    optparse removes positional arguments one at a time using del rargs[0], causing quadratic performance due to repeated list shifting. With 200k arguments, parsing takes ~2.5s instead of ~8ms.

    I changed it to remove consecutive positional arguments in a single operation using del rargs[:end], keeping option handling and callbacks unchanged.

    FYI I used caude code to investigate and prepare the fix, then verified it myself with benchmarks, the full test suite, and a fuzz test covering ~200k random argument lists. The output matched the old implementation.

  5. thejesh23 commented on Dec 4, 2026

    @thejesh23
    ContributorAuthor

    command-line tool that still uses optparse being handed a long list of file paths

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    AI-needs-explanationstdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions