[issue16399] argparse: append action with default list adds to list instead of overriding

paul j3 report at bugs.python.org
Sun Oct 2 19:05:19 EDT 2016


paul j3 added the comment:

It may help to know something about how defaults are handled - in general.

`add_argument` and `set_defaults` set the `default` attribute of the Action (the object created by `add_argument` to hold all of its information).  The default `default` is `None`.

At the start of `parse_args`, a fresh Namespace is created, and all defaults are loaded into it (I'm ignoring some details).

The argument strings are then parsed, and individual Actions update the Namespace with their values, via their `__call__` method.

At the end of parsing it reviews the Namespace.  Any remaining defaults that are strings are evaluated (passed through `type` function that converts a commandline string).  The handling of defaults threads a fine line between giving you maximum power, and keeping things simple and predictable.

The important thing for this issue is that the defaults are loaded into the Namespace at the start of parsing.

The `append` call fetches the value from the Namespace, replaces it with `[]` if it is None, appends the new value(s), and puts it back on the Namespace.  The first `--foo` append is handled in just the same way as the 2nd and third (fetch, append, and put back).  The first can't tell that the list it fetches from the namespace came from the `default` as opposed to a previous `append`.  

The `__call__` for `append` was intentionally kept simple, and predictable.  As I demonstrated earlier it is possible to write an `append` that checks the namespace value against some default, and does something different.  But that is more complicated.

The simplest alternative to this behavior is to leave the default as None.  If after parsing the value is still None, put the desired list (or any other object) there.  

The primary purpose of the parser is to parse the commandline - to figure out what the user wants to tell you.  There's nothing wrong with tweaking (and checking) the `args` Namespace after parsing.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16399>
_______________________________________


More information about the Python-bugs-list mailing list