[issue42973] argparse: mixing optional and positional arguments... not again

Glenn Linderman report at bugs.python.org
Mon Jan 25 22:59:18 EST 2021


Glenn Linderman <v+python at g.nevcal.com> added the comment:

OK, I think I see what you are doing here. Thanks for your responses.

And probably it is the bare-bones minimum feature that allows user-implementation of "as complex as desired" combinations of optionals and context-sensitive positionals.

In the docs fruits example, though, I think the input and output are inconsistent: you have a brown banana reported as yellow?

I guess I could think of enhancements to simplify common cases. For example, each positional might want to track/save values for some number of optionals. So one could write custom code to do that, like your fruit basket, or one could imagine a canned approach, where the list of optionals was passed as a parameter when defining the positionals.  This could be built as a wrapper for add_argument, that would call a more general version of the AddFruit Action.  Perhaps a special parameter could also indicate saving the values of all optionals at the point of parsing the positional, giving each positional a complete set of optionals that apply.

Your feature of having the optional apply to only one positional would be a harder thing, especially if you wanted to have both kinds of optionals: that apply to the next positional, or that apply to all following positionals. But hmm.  Maybe not much harder: just have two lists of optionals passed to the positional: a list of each kind.

Does the namespace still contain the default value for an optional after it has been used?  It looks like it might, so your fruit example could be reduced to not needing the DEFAULT_COLOR variable, but rather change references to it to use 

  self._get_default_metavar_for_positional(action) 

?  That avoids using a global variable, and is for more helpful for the "list of optionals to be reset on each use" rather than re-creating the more complex data structure required to hold all the defaults.

I'm not sure how that plays with optionals that use append or append_const storage methods, nor do I fully understand the comment in "def _copy_items(items):"

I think if you could avoid the global variable, your implementation would be stronger. And if you provide, either as a sample subclass, or argparse new feature, the ability to do the things I mention here, it would be even stronger, as it would allow the user to deal with the more powerful capabilities without needing as much understanding of argparse internals.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42973>
_______________________________________


More information about the Python-bugs-list mailing list