Skip to content

Feature request: event_parser envelopes should handle unions of BaseModels #2734

Closed
@dcheno

Description

@dcheno

Use case

Pydantic supports parsing unions of BaseModel types. This can be pretty handy when a lambda might accept a few different event types.

Example: a callback handler lambda might process an error response or a success response type. These might have different fields.

The current implementation of BaseEnvelope will error if you pass a Union or Annotated Union to the model field. This is because neither of those types have a parse_raw or parse_obj method which BaseModel expects.

Solution/User Experience

I believe this can mostly be taken care of by switching from using model.parse_raw and model.parse_obj here in BaseEnvelope to use pydantic.parse_obj_as and pydantic.parse_raw_as (available from pydantic 1.7 onwards so should match this projects dependencies). Docs here.

Happy to work on a PR, just wanted to check in here before I did too much work.

Alternative solutions

1. I've gotten around this in the past by just parsing the parent type in `event_parser`. For example, parsing `EventBridgeModel`, then parsing the `detail` myself using `parse_obj_as`.
2. This can also be solved on a case-by-case basis by rearchitecting the event structure so that the Union takes place within the model being parsed, but changing the event fields isn't always an option in existing codebases.

Acknowledgment

Metadata

Metadata

Assignees

Labels

breaking-changeBreaking changefeature-requestfeature requestv3Features that will be included in Powertools v3.

Type

No type

Projects

Status

Shipped

Relationships

None yet

Development

No branches or pull requests

Issue actions