Skip to content

argparser: Allow optional bool flags without values#43469

Open
antznette1 wants to merge 2 commits intohuggingface:mainfrom
antznette1:feat/hfargparser-optional-bool-flag
Open

argparser: Allow optional bool flags without values#43469
antznette1 wants to merge 2 commits intohuggingface:mainfrom
antznette1:feat/hfargparser-optional-bool-flag

Conversation

@antznette1
Copy link
Copy Markdown

Summary

Improve HfArgumentParser boolean UX so Optional[bool] arguments can be passed as flags without an explicit value.

What changed

  • Updated HfArgumentParser to treat typing.Optional[bool] (Union[bool, None]) the same as bool | None:
    • keeps default None
    • allows --flag (no value) to parse as True via nargs="?" + const=True
  • Updated unit tests in tests/utils/test_hf_argparser.py to reflect the new argparse configuration and verify --opt works without an explicit value.

@Rocketknight1
Copy link
Copy Markdown
Member

Is there an issue or reproducer to show the bug that this is fixing..?

@antznette1
Copy link
Copy Markdown
Author

Is there an issue or reproducer to show the bug that this is fixing..?

This is fixing a CLI UX bug in HfArgumentParser for Optional[bool].
Before this PR, an Optional[bool] flag behaves like a value-taking option, so passing the flag without a value errors (argparse expects an argument), even though most CLIs treat --flag as “enable”.

Reproducer:

from dataclasses import dataclass
from typing import Optional
from transformers.hf_argparser import HfArgumentParser
@DataClass
class Args:
opt: Optional[bool] = None
parser = HfArgumentParser(Args)
parser.parse_args_into_dataclasses(["--opt"]) # previously errors, now sets opt=True

This PR makes Optional[bool] behave like a standard boolean flag: --opt sets True, while still allowing explicit values (--opt false) and preserving the default None.

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 this pull request may close these issues.

2 participants