Skip to content

Conversation

@serhiy-storchaka
Copy link
Member

@serhiy-storchaka serhiy-storchaka commented Oct 2, 2024

Previously, the target list was copied every time the action was taken. Now only the default value is copied the first time the action is taken.

…nd 'extend'

Previously, the target list was copied every time the action was taken.
Now only the default value is copied the first time the action is taken.
Copy link
Contributor

@eendebakpt eendebakpt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The title of the PR should be changed to gh-96859: Optimize ... to link to a github issue. (gh-124745 is the number of an alternative PR)

@@ -0,0 +1,4 @@
Optimize :mod:`argparse` actions 'append', 'append_const' and 'extend' for
the case when the option is specified many times.
The targed list no longer copied every time the action is taken, only
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
The targed list no longer copied every time the action is taken, only
The target list is no longer copied every time the action is taken, only

def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest, None)
items = _copy_items(items)
if items is self.default:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I can tell this changes the behavior in some corner cases. For example, when parse_known_args() is called with a not empty namespace. The new code will only clone lists when default is set. The old code would have cloned any existing list. This matters if the caller has another reference to the same list.

Something like this

some_existing_list = []
ns = argparse.Namespace()
ns.setattr("foo", some_existing_list)

parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='append')
...

... = parser.parse_known_args(args=['--foo=xxx'], namespace=ns)

# At this point some_existing_list is ['xxx']

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. There are no tests for this (and some other corner cases).

@serhiy-storchaka serhiy-storchaka changed the title gh-124745: Optimize argparse actions 'append', 'append_const' and 'extend' gh-96859: Optimize argparse actions 'append', 'append_const' and 'extend' Oct 3, 2024
…yaxu.rst

Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

argparse.ArgumentParser is slow when parsing a very long option list

4 participants