Skip to content

Optional positional arguments throw an error in argparse #346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
joshlk opened this issue Mar 4, 2025 · 0 comments · May be fixed by #345
Open

Optional positional arguments throw an error in argparse #346

joshlk opened this issue Mar 4, 2025 · 0 comments · May be fixed by #345

Comments

@joshlk
Copy link
Contributor

joshlk commented Mar 4, 2025

Describe the bug
Optional positional arguments throw a "TypeError: 'required' is an invalid argument for positional" error in argparse.

To Reproduce

from dataclasses import dataclass
import simple_parsing

@dataclass
class Foo:
  a: int | None = simple_parsing.field(positional=True, default=None)

simple_parsing.parse(Foo)

Produces this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/python3.12/site-packages/simple_parsing/parsing.py", line 1044, in parse
    parsed_args = parser.parse_args(args)
                  ^^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/argparse.py", line 1895, in parse_args
    args, argv = self.parse_known_args(args, namespace)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/site-packages/simple_parsing/parsing.py", line 345, in parse_known_args
    self._preprocessing(args=args, namespace=namespace)
  File "/python3.12/site-packages/simple_parsing/parsing.py", line 549, in _preprocessing
    wrapped_dataclass.add_arguments(parser=self)
  File "/python3.12/site-packages/simple_parsing/wrappers/dataclass_wrapper.py", line 214, in add_arguments
    _ = group.add_argument(*wrapped_field.option_strings, **arg_options)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/argparse.py", line 1459, in add_argument
    kwargs = self._get_positional_kwargs(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/python3.12/argparse.py", line 1575, in _get_positional_kwargs
    raise TypeError(msg)
TypeError: 'required' is an invalid argument for positional

Issue resolved in PR: #345

@joshlk joshlk linked a pull request Mar 4, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant