-
I love the
Now I have some other functions that create the schema and I would like to type check with
As far as I can saw For reference, I wanted to add a similiar question from StackOverflow here. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Is there a reason you don't want to reuse Schema in your fancy function? def calculate_fancy()-> MyFancySchema:
...
return MyFancySchema(name="something", number=42) Perhaps you don't like that it does unnecessary runtime validation? Another option would be to define the TypedDict. Then assign that to the Schema. MyFancySchema(Schema):
data = FancyTypedDict
I think you're confusing how the api decorator works vs without it. When you make an API endpoint, with the decorator, you can set a response to a Schema class. The decorator function is converting the returned data into the Pydantic schema. That lets you return any object that can possibly be serialized via the schema. But that doesn't just magically happen otherwise and it isn't the type hint alone that makes it happen. The Python type hint on calculate_fancy has no effect on the code at all. So if you tell Python it returns a MyFancySchema but then you return a dict, mypy correctly raises an error. |
Beta Was this translation helpful? Give feedback.
-
Hmm, thanks for the hints. I am almost sure that you are right that I am confusing something, but I am really not sure what. Here is the typical code that I have. The API endpoint is something like this: @api.get( "/get_status", response={200: MyFancySchema, codes_4xx: JobResponseSchema})
def get_backend_status(request):
"""
Returns some fancy status.
"""
return calculate_fancy() The function now calls def calculate_fancy()-> MyFancyTypedDict:
return {'name': NameStr, 'number': 42} And the types would then be defined through: MyFancySchema(Schema):
name: str
number: int
MyFancyTypedDict(TypedDict):
name: str
number: int I am honestly not able to see how I could use your recommendation to use only one of the two |
Beta Was this translation helpful? Give feedback.
I'm not sure what you don't want calculate_fancy to return MyFancySchema. Then there is no need to convert it. Can you explain your use case?