Skip to content

Bug: Using @metrics.log_metrics and @event_parser on the same handler causes a type error. #3447

Closed
@brdskggs

Description

@brdskggs

Expected Behaviour

I expect to be able to use @metrics.log_metrics and @event_parser on the same Lambda handler. It doesn't work, regardless of order they are used to annotate the handler.

Current Behaviour

I get the following error in VS Code, according to Pylance:

Argument of type "(event: AgentQuery, context: LambdaContext) -> str" cannot be assigned to parameter "lambda_handler" of type "((Dict[Unknown, Unknown], Any) -> Any) | ((Dict[Unknown, Unknown], Any, Dict[Unknown, Unknown] | None) -> Any) | None" in function "__call__"
  Type "(event: AgentQuery, context: LambdaContext) -> str" cannot be assigned to type "((Dict[Unknown, Unknown], Any) -> Any) | ((Dict[Unknown, Unknown], Any, Dict[Unknown, Unknown] | None) -> Any) | None"
    Type "(event: AgentQuery, context: LambdaContext) -> str" cannot be assigned to type "(Dict[Unknown, Unknown], Any) -> Any"
      Parameter 1: type "Dict[Unknown, Unknown]" cannot be assigned to type "AgentQuery"
        "Dict[Unknown, Unknown]" is incompatible with "AgentQuery"
    Type "(event: AgentQuery, context: LambdaContext) -> str" cannot be assigned to type "(Dict[Unknown, Unknown], Any, Dict[Unknown, Unknown] | None) -> Any"
      Function accepts too many positional parameters; expected 2 but received 3
        Parameter 1: type "Dict[Unknown, Unknown]" cannot be assigned to type "AgentQuery"
          "Dict[Unknown, Unknown]" is incompatible with "AgentQuery"
Argument missing for parameter "context"

Code snippet

import json
from typing import List

from aws_lambda_powertools import Logger, Metrics
from aws_lambda_powertools.utilities.parser import BaseModel, Field, event_parser
from aws_lambda_powertools.utilities.typing import LambdaContext


logger = Logger()
metrics = Metrics()


class AgentQuery(BaseModel):
    username: str
    user_query: str


@logger.inject_lambda_context
@metrics.log_metrics(capture_cold_start_metric=True)
@event_parser(model=AgentQuery)
def lambda_handler(event: AgentQuery, context: LambdaContext):
    logger.info("hi")


### Possible Solution

Parser and Event Sources mutate the event, but `log_metrics` expect a dict.

Potential fix is to update type annotations for handler passed to `log_metrics` to be `AnyCallableT`.

### Steps to Reproduce

Paste the code in VS Code, and look at the Problems tab highlighted by Pylance.

### Powertools for AWS Lambda (Python) version

latest

### AWS Lambda function runtime

3.9

### Packaging format used

PyPi

### Debugging logs

_No response_

Metadata

Metadata

Assignees

Labels

metricstypingStatic typing definition related issues (mypy, pyright, etc.)

Type

No type

Projects

Status

Shipped

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions