Skip to content

Commit

Permalink
🐛 Add support for an argument of type Optional[Tuple] and default v…
Browse files Browse the repository at this point in the history
…alue `None` (#757)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: svlandeg <svlandeg@github.com>
  • Loading branch information
3 people committed Apr 7, 2024
1 parent 5cee0af commit a0209aa
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
19 changes: 19 additions & 0 deletions tests/test_type_conversion.py
Expand Up @@ -29,6 +29,25 @@ def opt(user: Optional[str] = None):
assert "User: Camila" in result.output


def test_optional_tuple():
app = typer.Typer()

@app.command()
def opt(number: Optional[Tuple[int, int]] = None):
if number:
print(f"Number: {number}")
else:
print("No number")

result = runner.invoke(app)
assert result.exit_code == 0
assert "No number" in result.output

result = runner.invoke(app, ["--number", "4", "2"])
assert result.exit_code == 0
assert "Number: (4, 2)" in result.output


def test_no_type():
app = typer.Typer()

Expand Down
8 changes: 6 additions & 2 deletions typer/main.py
Expand Up @@ -645,10 +645,14 @@ def internal_convertor(value: Sequence[Any]) -> Optional[List[Any]]:

def generate_tuple_convertor(
types: Sequence[Any],
) -> Callable[[Tuple[Any, ...]], Tuple[Any, ...]]:
) -> Callable[[Optional[Tuple[Any, ...]]], Optional[Tuple[Any, ...]]]:
convertors = [determine_type_convertor(type_) for type_ in types]

def internal_convertor(param_args: Tuple[Any, ...]) -> Tuple[Any, ...]:
def internal_convertor(
param_args: Optional[Tuple[Any, ...]],
) -> Optional[Tuple[Any, ...]]:
if param_args is None:
return None
return tuple(
convertor(arg) if convertor else arg
for (convertor, arg) in zip(convertors, param_args)
Expand Down

0 comments on commit a0209aa

Please sign in to comment.