Python -Typ Annotation von Spezialformen mit Pydantic und MyPyPython

Python-Programme
Anonymous
 Python -Typ Annotation von Spezialformen mit Pydantic und MyPy

Post by Anonymous »

Code: Select all

python 3.13
pydantic 2.10.5
mypy 1.16.0
Wie kann die Rückgabe von typing ordnungsgemäß kommentieren.

Code: Select all

from functools import partial
from typing import Annotated

from pydantic import AfterValidator, BaseModel

def validate_smth(value: str, context: str) -> str:
if value == "test":
print(f"Validated {value}")
else:
raise ValueError(f"Value {value} is not allowed in context {context}")
return value

def return_annotated_type(context: str = "") -> type: # error: Incompatible return value type (got "", expected "type")  [return-value]
validator = partial(validate_smth, context=context)
return Annotated[str, AfterValidator(validator)]

class MyModel(BaseModel):
field: return_annotated_type(context="test") # error: Invalid type comment or annotation  [valid-type]
# note: Suggestion: use return_annotated_type[...] instead of return_annotated_type(...)

MyModel.model_validate({"field": "test"})

< /code>
Ich habe es versucht: < /p>
def return_annotated_type(context: str = "") -> Annotated[str, AfterValidator]:
# error: Incompatible return value type (got "", expected "str")  [return-value]
< /code>
def return_annotated_type(context: str = "") -> Any:
# no error here, but i don't like that Any is too broad.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post