Skip to content

Commit

Permalink
simplify pydantic type conversion using pydantic.TypeAdapter
Browse files Browse the repository at this point in the history
  • Loading branch information
lachaib committed Sep 4, 2024
1 parent b70d5a6 commit 0a793f6
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,17 @@
from pathlib import Path
from traceback import FrameSummary, StackSummary
from types import TracebackType
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from uuid import UUID

import click
Expand Down Expand Up @@ -69,14 +79,11 @@ def is_pydantic_type(type_: Any) -> bool:
def pydantic_convertor(type_: type) -> Callable[[str], Any]:
"""Create a convertor for a parameter annotated with a pydantic type."""
T: TypeAlias = type_ # type: ignore[valid-type]

@pydantic.validate_call
def internal_convertor(value: T) -> T:
return value
adapter: pydantic.TypeAdapter[T] = pydantic.TypeAdapter(type_)

def convertor(value: str) -> T:
try:
return internal_convertor(value)
return adapter.validate_python(value)
except pydantic.ValidationError as e:
error_message = e.errors(
include_context=False, include_input=False, include_url=False
Expand Down

0 comments on commit 0a793f6

Please sign in to comment.