Repository navigation
Replies: 2 comments
This comment was marked as spam.
This comment was marked as spam.
|
Hello @morp007, I reproduced this issue with Typer 0.26.3 and identified why the custom parser is called twice. When This explains why:
Solution 1: Make the parser idempotentThe smallest change is to allow the parser to recognise already-converted values: def parse_custom_class(value: str | CustomClass) -> CustomClass:
if isinstance(value, CustomClass):
return value
return CustomClass(value * 2)This preserves your existing custom-type annotation and avoids converting the object twice. Solution 2: Perform conversion inside the commandAlternatively, declare the CLI option as a string and perform the conversion once: def main(
custom_opt: Annotated[str, typer.Option(prompt=True)] = "Foo",
):
custom_opt_obj = parse_custom_class(custom_opt)
print(f"--custom-opt is {custom_opt_obj.value}")This avoids relying on how Typer invokes custom parsers during prompting. VerificationI ran nine regression tests using Python 3.13.5 and Typer 0.26.3, covering:
The original parser reproduced the reported error, while both workarounds passed all three scenarios. Result: 9 tests passed. I also inspected the Typer 0.29.1 source, which retains the relevant double-processing path, but have not runtime-tested that release. For your existing implementation, I recommend Solution 1 because it requires the smallest change. |
Uh oh!
There was an error while loading. Please reload this page.
First Check
Commit to Help
Example Code
Description
promt=Truefortyper.Optioncustom_optcustom_opt, promt somethingThe error arises due to the fact that
parserwas called twice:stris passed to theparserCustomClassfrom the previous call is passed to the parserWhy
parsercalled twice with promt?.. Is this a bug or an example needs to be updated?Operating System
Linux, Windows, macOS
Operating System Details
No response
Typer Version
0.16.0
Python Version
3.12.11
Additional Context
No response
All reactions