This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author wodny85
Recipients Thermi, joker, paul.j3, rhettinger, terry.reedy, wodny85
Date 2021-09-03.07:39:47
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1630654787.65.0.767995404878.issue44748@roundup.psfhosted.org>
In-reply-to
Content
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)
```
History
Date User Action Args
2021-09-03 07:39:47wodny85setrecipients: + wodny85, rhettinger, terry.reedy, paul.j3, Thermi, joker
2021-09-03 07:39:47wodny85setmessageid: <1630654787.65.0.767995404878.issue44748@roundup.psfhosted.org>
2021-09-03 07:39:47wodny85linkissue44748 messages
2021-09-03 07:39:47wodny85create