Skip to content

LoggerAdapter is typed as a generic but using it as such raises an error at runtime #7855

Closed

Description

@babolivier

With the following code:

class ContextLoggingAdapter(logging.LoggerAdapter):
    def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]:
        ...

mypy raises the following type-arg error : error: Missing type parameters for generic type "LoggerAdapter"

According to this type stub it's typed as a generic and should be passed the type of the logger it's an adapter for. However, changing the code into this:

class ContextLoggingAdapter(logging.LoggerAdapter[logging.Logger]):
    def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]:
        ...

makes mypy happy but raises an error at runtime: TypeError: 'type' object is not subscriptable

I'm not sure if this is an issue with the stubs or with mypy (and I'm not fully sure how they interact), so apologies if this issue should have been created on https://github.com/python/mypy instead (feel free to transfer it there if that's the case).

Activity

  1. AlexWaygood commented on May 17, 2022

    @AlexWaygood
    Member

    You created the issue in the right place :) and, this is a problem we're aware of.

    LoggerAdapter will actually be generic at runtime on 3.11, because of this very issue: python/cpython#92129

    In the meantime, however, @Akuli's advice here is probably the best way around this issue: #5954 (comment):

    import logging
    from typing import TYPE_CHECKING, Tuple, Any
    
    if TYPE_CHECKING:
        _LoggerAdapter = logging.LoggerAdapter[logging.Logger]
    else:
        _LoggerAdapter = logging.LoggerAdapter
    
    class ContextLoggingAdapter(_LoggerAdapter):
        def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]:
            ...

    There's also some great mypy docs on this problem here: https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime

  2. babolivier commented on May 17, 2022

    @babolivier
    Author

    That makes sense, thanks a lot for the details and references :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions