Skip to content

Commit

Permalink
refactor(parser): only infer type hints when necessary (#4183)
Browse files Browse the repository at this point in the history
fix(parser): only infer type hints when necessary

This was breaking in codebases that conditionally import type hints using the `typing.TYPE_CHECKING` constant as described in [PEP 563](https://peps.python.org/pep-0563/#runtime-annotation-resolution-and-type-checking).

When the model is provided, there is no need to infer anything.

Signed-off-by: Raymond Butcher <[email protected]>
  • Loading branch information
raymondbutcher authored Apr 23, 2024
1 parent 24acbfe commit fe26d1c
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions aws_lambda_powertools/utilities/parser/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,17 @@ def handler(event: Order, context: LambdaContext):
When envelope given does not implement BaseEnvelope
"""

# The first parameter of a Lambda function is always the event
# This line get the model informed in the event_parser function
# or the first parameter of the function by using typing.get_type_hints
type_hints = typing.get_type_hints(handler)
model = model or (list(type_hints.values())[0] if type_hints else None)
if model is None:
raise InvalidModelTypeError(
"The model must be provided either as the `model` argument to `event_parser`"
"or as the type hint of `event` in the handler that it wraps",
)
# The first parameter of a Lambda function is always the event.
# Get the first parameter's type by using typing.get_type_hints.
type_hints = typing.get_type_hints(handler)
if type_hints:
model = list(type_hints.values())[0]
if model is None:
raise InvalidModelTypeError(
"The model must be provided either as the `model` argument to `event_parser`"
"or as the type hint of `event` in the handler that it wraps",
)

if envelope:
parsed_event = parse(event=event, model=model, envelope=envelope)
Expand Down

0 comments on commit fe26d1c

Please sign in to comment.