Skip to content

[Code scan] Non-string variant choices raise raw TypeError #119

Description

@njzjz

This issue was found by a Codex global code scan of the repository.

Affected code:

dargs/dargs/dargs.py

Lines 898 to 913 in b4db564

def get_choice(self, argdict: dict, path: list[str] | None = None) -> Argument:
if self.flag_name in argdict:
tag = argdict[self.flag_name]
if tag in self.choice_dict:
return self.choice_dict[tag]
elif tag in self.choice_alias:
return self.choice_dict[self.choice_alias[tag]]
else:
raise ArgumentValueError(
path,
f"get invalid choice `{tag}` for flag key `{self.flag_name}`."
+ did_you_mean(
tag,
list(self.choice_dict.keys()) + list(self.choice_alias.keys()),
),
)

dargs/dargs/dargs.py

Lines 1273 to 1289 in b4db564

def did_you_mean(choice: str, choices: Iterable[str]) -> str:
"""Get did you mean message.
Parameters
----------
choice : str
the user's wrong choice
choices : list[str]
all the choices
Returns
-------
str
did you mean error message
"""
matches = difflib.get_close_matches(choice, choices)
return f"Did you mean: {matches[0]}?" if matches else ""

Problem:
When a variant flag value is not a string, Variant.get_choice() passes it to did_you_mean(), which calls difflib.get_close_matches(). Non-string values such as 1 or None raise raw TypeError from inside difflib instead of a structured dargs ArgumentError.

Reproducer:

from dargs import Argument, Variant

arg = Argument("base", dict, sub_variants=[Variant("kind", [Argument("a", dict)])])
arg.check_value({"kind": 1})

Observed behavior:

TypeError: 'int' object is not iterable

Expected behavior:
Invalid non-string variant tags should raise a dargs ArgumentTypeError or ArgumentValueError with the argument path and expected choices.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions