Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
babolivier opened this issue May 17, 2022 · 2 comments

Comments

@babolivier
Copy link

babolivier commented May 17, 2022

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).

@AlexWaygood
Copy link
Member

AlexWaygood commented May 17, 2022

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

@babolivier
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants