Skip to content

Commit

Permalink
Fixed bug with is_flag and type inference (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
couling authored Feb 13, 2024
1 parent fea8bee commit 18c6668
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion dataclass_click/dataclass_click.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def _patch_click_types(
for key, annotation in annotations.items():
hint: typing.Type[Any]
_, hint = _strip_optional(type_hints[key])
if "type" not in annotation.kwargs:
if "type" not in annotation.kwargs and not annotation.kwargs.get("is_flag", False):
if hint in complete_type_inferences:
annotation.kwargs["type"] = complete_type_inferences[hint]
else:
Expand Down
36 changes: 36 additions & 0 deletions tests/test_end_to_end.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,42 @@ def main(*args, **kwargs):
assert isinstance(results[0][0][0].foo, inferrable_type)


@pytest.mark.parametrize("args", [{}, {"is_flag": False}], ids=["no_args", "is_flag_false"])
def test_type_inference_raises(args: dict[str, Any]):

class UnknownClass:
pass

@dataclass
class Config:
foo: Annotated[UnknownClass, option(**args)]

with pytest.raises(TypeError):

@click.command()
@dataclass_click(Config)
def main(*args, **kwargs):
pass


@pytest.mark.parametrize("args", [{"type": click.INT}, {"is_flag": True}], ids=["type", "is_flag_true"])
def test_types_not_inferred(args: dict[str, Any]):

class UnknownClass:
pass

@dataclass
class Config:
foo: Annotated[UnknownClass, option(**args)]

# Make sure no exception is raised.
# See test_type_inference_raises() for the counter example
@click.command()
@dataclass_click(Config)
def main(*args, **kwargs):
pass


def test_inferred_option_name():
"""Test that the option name can be inferred from the attribute name"""

Expand Down

0 comments on commit 18c6668

Please sign in to comment.