Repository navigation
Pydantic constraints and validators in Annotated (e.g. PositiveInt, Field(gt=0), AfterValidator) are silently ignored #2024
First Check
Example Codefrom typing import Annotated
from pydantic import AfterValidator, Field, PositiveInt
import typer
app = typer.Typer()
@app.command()
def main(
count: PositiveInt,
limit: Annotated[int, Field(gt=0), typer.Option()] = 1,
tag: Annotated[str, AfterValidator(str.upper), typer.Option()] = "abc",
):
print(f"count={count}, limit={limit}, tag={tag}")
if __name__ == "__main__":
app()DescriptionAfter #1831 introduced Pydantic validation for CLI parameters, Pydantic constraints and validators inside
Nested usages like Operating SystemmacOS Operating System DetailsNo response Project Version0.29.2 Python Version3.13.5 Additional ContextLooking into the source, non-Typer
I'd be happy to open a PR to preserve non-Typer |
Replies: 2 comments 2 replies
|
Your root-cause analysis in While waiting for maintainer feedback on your PR, the cleanest workaround in from typing import Annotated, Any
from pydantic import AfterValidator, Field, PositiveInt, TypeAdapter
import typer
app = typer.Typer()
def pydantic_validator(tp: Any):
adapter = TypeAdapter(tp)
def _validate(value: Any) -> Any:
try:
return adapter.validate_python(value)
except Exception as exc:
raise typer.BadParameter(str(exc)) from exc
return _validate
UpperStr = Annotated[str, AfterValidator(str.upper)]
@app.command()
def main(
count: Annotated[int, typer.Argument(callback=pydantic_validator(PositiveInt))],
limit: Annotated[int, typer.Option(callback=pydantic_validator(Annotated[int, Field(gt=0)]))] = 1,
tag: Annotated[str, typer.Option(callback=pydantic_validator(UpperStr))] = "abc",
):
print(f"count={count}, limit={limit}, tag={tag}")
if __name__ == "__main__":
app()Preserving non- |
|
Hi @LowmistLMT, thanks for the detailed report! Yes, this is something we should handle. Considering the amount of refactoring we're doing right now though, we're not currently accepting user PRs for this functionality, as it would only end up conflicting with work we already have planned. But this is definitely on our internal TODO list 🙏 |
Hi @LowmistLMT, thanks for the detailed report!
Yes, this is something we should handle. Considering the amount of refactoring we're doing right now though, we're not currently accepting user PRs for this functionality, as it would only end up conflicting with work we already have planned. But this is definitely on our internal TODO list 🙏