Skip to content

Commit 4a63098

Browse files
amyreesezsol
andauthored
gh-116159: argparse: performance improvement parsing large number of options (#116162)
When parsing positional vs optional arguments, the use of min with a list comprehension inside of a loop results in quadratic time based on the number of optional arguments given. When combined with use of prefix based argument files and a large number of optional flags, this can result in extremely slow parsing behavior. This replaces the min call with a simple loop with a short circuit to break at the next optional argument. Co-authored-by: Zsolt Dollenstein <[email protected]>
1 parent 7b47943 commit 4a63098

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

Lib/argparse.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2153,10 +2153,11 @@ def consume_positionals(start_index):
21532153
while start_index <= max_option_string_index:
21542154

21552155
# consume any Positionals preceding the next option
2156-
next_option_string_index = min([
2157-
index
2158-
for index in option_string_indices
2159-
if index >= start_index])
2156+
next_option_string_index = start_index
2157+
while next_option_string_index <= max_option_string_index:
2158+
if next_option_string_index in option_string_indices:
2159+
break
2160+
next_option_string_index += 1
21602161
if start_index != next_option_string_index:
21612162
positionals_end_index = consume_positionals(start_index)
21622163

0 commit comments

Comments
 (0)