[issue43160] argparse: add extend_const action
Tony Lykke
report at bugs.python.org
Tue Feb 9 02:51:49 EST 2021
Tony Lykke <hi at tonylykke.com> added the comment:
Perhaps the example I added to the docs isn't clear enough and should be changed because you're right, that specific one can be served by store_const. Turns out coming up with examples that are minimal but not too contrived is hard! Let me try again with a longer example that hopefully shows more clearly how the existing action's behaviours differ from my patch.
parser = argparse.ArgumentParser()
parser.add_argument("--foo", action="append", default=[])
parser.add_argument("--append", action="append_const", dest="foo", const=["a", "b"])
parser.add_argument("--store", action="store_const", dest="foo", const=["a", "b"])
When run on master the following behaviour is observed:
--foo a --foo b --foo c
Namespace(foo=['a', 'b', 'c'])
--foo c --append
Namespace(foo=['c', ['a', 'b']])
--foo c --store
Namespace(foo=['a', 'b'])
--store --foo a
Namespace(foo=['a', 'b', 'c'])
If we then add the following:
parser.add_argument("--extend", action="extend_const", dest="foo", const=["a", "b"])
and then run it with my patch the following can be observed:
--foo c --extend
Namespace(foo=['c', 'a', 'b'])
--extend --foo c
Namespace(foo=['a', 'b', 'c'])
store_const is actually a pretty close fit, but the way it makes order significant (specifically in that it will silently drop prev values) seems like it'd be rather surprising to users and makes it a big enough footgun for this use case that I don't think it's a satisfactory alternative.
> I suspect users of your addition will get a surprise if they aren't careful to provide a list or tuple 'const'
I did consider that, but I don't think they'd get any more of a surprise than for doing the same with list.extend vs list.append.
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43160>
_______________________________________
More information about the Python-bugs-list
mailing list