Open UlfurOrn opened 2 days ago
Thanks for opening your first issue here! We'll come back to you as soon as we can. In the meantime, check out the #python channel on our Powertools for AWS Lambda Discord: Invite link
If you need any more details please let me know 🙏
Hi @UlfurOrn! Thanks for reporting this issue! I see other people complaining about the same thing in Pydantic and with no effective solution. It really seems like validating JSON against a model that can has a type of another model is a limitation in Pydantic.
But talking about the Powertools side, I was able to reproduce the problem here and I can confirm this is creating some problems. Due to this seems to be a limitation in Pydantic I think we can put the validation code in a try/exception block and if this raises a NotImplementedError
we try to validate with validate_python
instead of validate_json
. Something like this:
logger.debug("parsing event against model")
try:
if isinstance(data, str):
logger.debug("parsing event as string")
return adapter.validate_json(data)
return adapter.validate_python(data)
except NotImplementedError:
logger.debug("fallback to validate using python")
data = json.loads(data)
return adapter.validate_python(data)
I still need to think in a more optimized code for this, but this seems to fix the Pydantic limitation.
Either this part of the type hint needs to be removed or something needs to happen in the validation logic itself.
Removing the type hint part is not a good solution because we can break customers that are relying in this possible type and using classes instead of instances of those classes. We never know how our customers are using this project and it is better to avoid breaking things.
I'd like to hear your thoughts.
Expected Behaviour
Parsing an event/field from JSON containing a field with the type
RawDictOrModel
(likeEventBridgeModel
) should work.Current Behaviour
Parsing an event/field from JSON containing a field with the type
RawDictOrModel
(likeEventBridgeModel
) results in an error:Code snippet
Possible Solution
This is being caused due to the
RawDictOrModel
type being a union of multiple types includingtype[BaseModel]
which is causing the issue.e.g. when powertools attempts to pydantic to load the JSON (using
model_validate_json
). It tries to validate the field againsttype[BaseModel]
which does not seem to be allowed in a JSON parsing context.Either this part of the type hint needs to be removed or something needs to happen in the validation logic itself.
Steps to Reproduce
See the code snippets. This only happens when the detail field (or any field of the type
RawDictOrModel
) of theEventBridgeModel
actually contains some data.Powertools for AWS Lambda (Python) version
latest
AWS Lambda function runtime
3.11
Packaging format used
Lambda Layers
Debugging logs
No response