2

In the following setup I define a protocol LambdaContext, and extend this protocol in LogContext by subclassing. I then define a function which takes in a LogContext as an argument. However, this function is decorated by a function called main which expects an argument of type: LambdaContext. Therefore, I am a bit confused why mypy is complaining that main is receiving a callable function with LogContext as its argument. LogContext still implements the LambdaContext Protocol:

from typing import Any, Callable, Container, Dict, Protocol


class LambdaContext(Protocol):
    """Represents the context object passed to main_handler lambda functions"""
    get_remaining_time_in_millis: Callable[[], int]
    ...


class LogContext(LambdaContext, Protocol):
    def items(self) -> None:
        # An example function which extends LambdaContext Protocol
        ...


LambdaFunctionHandler = Callable[[LambdaContext], Any]


def main(function: LambdaFunctionHandler) -> Any:
    ...


@main
def main_handler(context: LogContext):
    ...

mypy results in the following error.:

error: Argument 1 to "main" has incompatible type "Callable[[LogContext], Any]"; expected "Callable[[LambdaContext], Any]"

As far as my understanding goes, The LogContext extends the LambdaContext Protocol. While LogContext is more specific and in this example defines an additional function items, it still implements LambdaContext Protocol by subclassing it. Any ideas would be greatly appreciated and can hopefully clarify my understanding.

Many thanks.

Zachy
  • 88
  • 5
  • Does this answer your question? [How to make Mypy deal with subclasses in functions as expected](https://stackoverflow.com/questions/56924692/how-to-make-mypy-deal-with-subclasses-in-functions-as-expected) – joel Feb 01 '22 at 18:54

0 Answers0