Skip to content

Commit f34aa4a

Browse files
🐛 Fix list convertor with an empty list default factory (#1350)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent df2359a commit f34aa4a

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

tests/test_others.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from typer.main import solve_typer_info_defaults, solve_typer_info_help
1515
from typer.models import ParameterInfo, TyperInfo
1616
from typer.testing import CliRunner
17+
from typing_extensions import Annotated
1718

1819
from .utils import requires_completion_permission
1920

@@ -170,6 +171,22 @@ def main(
170171
assert "Hello World" in result.stdout
171172

172173

174+
def test_empty_list_default_generator():
175+
def empty_list() -> typing.List[str]:
176+
return []
177+
178+
app = typer.Typer()
179+
180+
@app.command()
181+
def main(
182+
names: Annotated[typing.List[str], typer.Option(default_factory=empty_list)],
183+
):
184+
print(names)
185+
186+
result = runner.invoke(app)
187+
assert "[]" in result.output
188+
189+
173190
def test_completion_argument():
174191
file_path = Path(__file__).parent / "assets/completion_argument.py"
175192
result = subprocess.run(

typer/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -629,8 +629,8 @@ def generate_list_convertor(
629629
convertor: Optional[Callable[[Any], Any]], default_value: Optional[Any]
630630
) -> Callable[[Optional[Sequence[Any]]], Optional[List[Any]]]:
631631
def internal_convertor(value: Optional[Sequence[Any]]) -> Optional[List[Any]]:
632-
if value is None or len(value) == 0:
633-
return default_value
632+
if (value is None) or (default_value is None and len(value) == 0):
633+
return None
634634
return [convertor(v) if convertor else v for v in value]
635635

636636
return internal_convertor

0 commit comments

Comments
 (0)