Message400971
Another way to play with the defaults is to use argparse.SUPPRESS. With such a default, the argument does not appear in the namespace, unless provided by the user.
In [2]: p = argparse.ArgumentParser()
...: p.add_argument('--foo', default=argparse.SUPPRESS, help='foo help')
...: p.add_argument('--bar', default='default')
...: p.add_argument('--baz');
In [3]: args = p.parse_args([])
In [4]: args
Out[4]: Namespace(bar='default', baz=None)
Such a namespace can be used to update an existing dict (such as from a config file), changing only keys provided by user (and ones where SUPPRESS does not make sense, such as store_true and positionals).
In [5]: adict = {'foo':'xxx', 'bar':'yyy', 'baz':'zzz'}
In [6]: adict.update(vars(args))
In [7]: adict
Out[7]: {'foo': 'xxx', 'bar': 'default', 'baz': None}
User provided value:
In [8]: args = p.parse_args(['--foo','foo','--baz','baz'])
In [9]: args
Out[9]: Namespace(bar='default', baz='baz', foo='foo')
In this code sample I used Ipython. That IDE uses (or at least did some years ago) a custom integration of config and argparse. System default config file(s) set a large number of parameters. Users are encouraged to write their own profile configs (using provided templates). On starting a session, the config is loaded, and used to populate a parser, with arguments, helps and defaults. Thus values are set or reset upto 3 times - default, profile and commandline.
I for example, usually start an ipython session with an alias
alias inumpy3='ipython3 --pylab qt --nosep --term-title --InteractiveShellApp.pylab_import_all=False --TerminalInteractiveShell.xmode=Plain'
Regarding this bug/issue, if someone can come up with a clever tweak that satisfies Thermi, is potentially useful to others, and is clearly backward compatible, great.
But if this issue requires a less-than-ideal-compatible patch, or greater integration of config and argparse, then it needs to be developed as a separate project and tested on PyPi. Also search PyPi; someone may have already done the work. |
|
Date |
User |
Action |
Args |
2021-09-03 00:56:47 | paul.j3 | set | recipients:
+ paul.j3, rhettinger, terry.reedy, Thermi, joker, wodny85 |
2021-09-03 00:56:47 | paul.j3 | set | messageid: <1630630607.34.0.70676626748.issue44748@roundup.psfhosted.org> |
2021-09-03 00:56:47 | paul.j3 | link | issue44748 messages |
2021-09-03 00:56:46 | paul.j3 | create | |
|