mypy and logging.Logger subclasses #980
-
|
EDIT: I added a pull request in python/typeshed to enable workaround 2.
So, let's say we want to use a custom
However, the proposed solutions, either monkey-patching or using a The issueSuppose we have the following setup code: In config/base module we define a new Logger subclass: class MyLogger(logging.Logger):
...
logging.setLoggerClass(MyLogger)
logger = logging.getLogger(__name__)Then in submodules: import logging
logger = logging.getLogger(__name__)We will get type errors (undefined attribute) each and every time we do Possible workaroundsSo I was wondering, what could be an acceptable solution? Plastering Workaround proposal 1 - add explicit type hint for the subclassimport logging
from mymodule.logger import MyLogger
logger: MyLogger = logging.getLogger(__name__)This does not quite work because def getLogger(name: Optional[str] = ...) -> Logger: ...Instead, we would need something like T = TypeVar("T", bound=Logger)
def getLogger(name: Optional[str] = ...) -> T: ...In conjunction with a change of how Workaround proposal 2 - Import the Logger object and create a child.from mymodule.logger import logger # returns actual object
logger = logger.getChild(__name__)Here are 2 issues:
def getChild(self, suffix: str) -> Logger: ...However, we need something along the lines of T = TypeVar("T", bound=Logger)
def getChild(self: T, suffix: str) -> T: ...Cf. python/mypy#1212 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
|
The second workaround seems better to me. It seems unlikely that
The source code for So As you said, we still need to change the definition of |
Beta Was this translation helpful? Give feedback.
-
|
Is there a proper workaround for this today? I'm actually not sure how applicable Workaround 2 is for custom Logger classes Edit: I just the linked blog post. I am certainly not keen on adding a partial typed for overriding parameters from the logging subclass |
Beta Was this translation helpful? Give feedback.
-
|
i call Please note:
|
Beta Was this translation helpful? Give feedback.
I opened an issue in typeshed: python/typeshed#6606