[docs] [issue16399] argparse: append action with default list adds to list instead of overriding
paul j3
report at bugs.python.org
Sun Oct 2 20:31:40 EDT 2016
paul j3 added the comment:
One thing that this default behavior does is allow us to append values to any object, just so long as it has the `append` method. The default does not have to be a standard list.
For example, in another bug/issue someone asked for an `extend` action. I could provide that with `append` and a custom list class
class MyList(list):
def append(self,arg):
if isinstance(arg,list):
self.extend(arg)
else:
super(MyList, self).append(arg)
This just modifies `append` so that it behaves like `extend` when given a list argument.
parser = argparse.ArgumentParser()
a = parser.add_argument('-f', action='append', nargs='*',default=[])
args = parser.parse_args('-f 1 2 3 -f 4 5'.split())
produces a nested list:
In [155]: args
Out[155]: Namespace(f=[['1', '2', '3'], ['4', '5']])
but if I change the `default`:
a.default = MyList([])
args = parser.parse_args('-f 1 2 3 -f 4 5'.split())
produces a flat list:
In [159]: args
Out[159]: Namespace(f=['1', '2', '3', '4', '5'])
I've tested this idea with an `array.array` and `set` subclass.
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16399>
_______________________________________
More information about the docs
mailing list