From fe26d1c9e1cb6478f1b4818363f251056948b4f1 Mon Sep 17 00:00:00 2001 From: Raymond Butcher Date: Tue, 23 Apr 2024 17:01:22 +0100 Subject: [PATCH] refactor(parser): only infer type hints when necessary (#4183) 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 --- .../utilities/parser/parser.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/aws_lambda_powertools/utilities/parser/parser.py b/aws_lambda_powertools/utilities/parser/parser.py index a9a89db8a6a..13893be8749 100644 --- a/aws_lambda_powertools/utilities/parser/parser.py +++ b/aws_lambda_powertools/utilities/parser/parser.py @@ -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)