wodny <[email protected]> added the comment:
I used a wrapper to default values. This gives me nice help message with
ArgumentDefaultsHelpFormatter and easy way to update a config file dictionary
with results from parse_args().
```python
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, Namespace
from dataclasses import dataclass
from typing import Any
@dataclass
class Default:
value: Any
def __str__(self):
return str(self.value)
@staticmethod
def remove_defaults(ns):
return Namespace(**{ k: v for k, v in ns.__dict__.items() if not
isinstance(v, Default)})
@staticmethod
def strip_defaults(ns):
return Namespace(**{ k: v.value if isinstance(v, Default) else v for k,
v in ns.__dict__.items() })
p = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
p.add_argument("--foo", "-f", default=Default(10), help="the foo arg")
p.add_argument("--bar", "-b", default=Default("big-bar"), help="the bar arg")
p.add_argument("--baz", "-z", default=True, help="the baz arg")
options = p.parse_args()
print(options)
print(Default.remove_defaults(options))
print(Default.strip_defaults(options))
```
```sh
$ ./arguments.py -b hello
Namespace(bar='hello', baz=True, foo=Default(value=10))
Namespace(bar='hello', baz=True)
Namespace(bar='hello', baz=True, foo=10)
$ ./arguments.py -b hello -h
usage: arguments.py [-h] [--foo FOO] [--bar BAR] [--baz BAZ]
optional arguments:
-h, --help show this help message and exit
--foo FOO, -f FOO the foo arg (default: 10)
--bar BAR, -b BAR the bar arg (default: big-bar)
--baz BAZ, -z BAZ the baz arg (default: True)
```
----------
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue44748>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com