Skip to content
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

🐛 Add support for an argument of type Optional[Tuple] and default value None #757

Merged
merged 9 commits into from
Apr 7, 2024
19 changes: 19 additions & 0 deletions tests/test_type_conversion.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Loading