swansonk14/typed-argument-parser

Unhandled error when parsing unrecognized arguments when using `explicit_bool=True`

zplizzi opened this issue · 2 comments

Here's a little demo:

from tap import Tap


class Stuff(Tap):
    test: bool = True

    def __init__(self):
        super().__init__(self, explicit_bool=True)


if __name__ == "__main__":
    args = Stuff().parse_args()
    print(args.test)

Then if I call this code with a mistyped argument (test.py --test_oops False), I get this error:

Traceback (most recent call last):
  File "stuff/test.py", line 12, in <module>
    args = DreamerParams().parse_args()
  File "/opt/venv/lib/python3.9/site-packages/tap/tap.py", line 441, in parse_args
    default_namespace = super(Tap, self).parse_args(args)
  File "/usr/lib/python3.9/argparse.py", line 1833, in parse_args
    self.error(msg % ' '.join(argv))
  File "/usr/lib/python3.9/argparse.py", line 2585, in error
    self.print_usage(_sys.stderr)
  File "/usr/lib/python3.9/argparse.py", line 2555, in print_usage
    self._print_message(self.format_usage(), file)
  File "/usr/lib/python3.9/argparse.py", line 2521, in format_usage
    return formatter.format_help()
  File "/usr/lib/python3.9/argparse.py", line 295, in format_help
    help = self._root_section.format_help()
  File "/usr/lib/python3.9/argparse.py", line 226, in format_help
    item_help = join([func(*args) for func, args in self.items])
  File "/usr/lib/python3.9/argparse.py", line 226, in <listcomp>
    item_help = join([func(*args) for func, args in self.items])
  File "/usr/lib/python3.9/argparse.py", line 320, in _format_usage
    prog = '%(prog)s' % dict(prog=self._prog)
  File "/opt/venv/lib/python3.9/site-packages/tap/tap.py", line 703, in __str__
    return pformat(self.as_dict())
  File "/opt/venv/lib/python3.9/site-packages/tap/tap.py", line 580, in as_dict
    raise ValueError('You should call `parse_args` before retrieving arguments.')
ValueError: You should call `parse_args` before retrieving arguments.

In fact, the problem isn't explicit_bool specifically, this problem occurs anytime you call super().__init__(self) in the initializer, and doesn't occur if you don't make this call. Am I doing something wrong here?

Did you mean to do

super().__init__(explicit_bool=True)

instead?

Good catch, that does seem to fix it. Thanks and sorry for the bother!