mypy and logging.Logger subclasses #980
Replies: 2 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.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
EDIT: I added a pull request in python/typeshed to enable workaround 2.
So, let's say we want to use a custom
logging.Logger
sub-class with additional methods e.g.trace
,verbose
,passed
,failed
that provide specialized formatting and/or use custom log-levels.However, the proposed solutions, either monkey-patching or using a
logging.Logger
subclass both do not work well with mypy, because the standard way to get a Logger is usinglogging.getLogger
which is unaware of the subclass. See also this blog post by Sam Hooke.The issue
Suppose we have the following setup code: In config/base module we define a new Logger subclass:
Then in submodules:
We will get type errors (undefined attribute) each and every time we do
logger.verbose
/logger.trace
etc. There was already a very brief discussion here python/typeshed#1801 without any good resolution.Possible workarounds
So I was wondering, what could be an acceptable solution? Plastering
# type: ignore
every time we uselogger.verbose
does not seem reasonable to me. I think there are two possibilities, which however currently are not quite compatible withmypy
.Workaround proposal 1 - add explicit type hint for the subclass
This does not quite work because
getLogger
has the following signature in typeshed/stdlib/logging`:Instead, we would need something like
In conjunction with a change of how
TypeVar
works: if no type hint is given assume the type is the bound type. This was discussed here python/mypy#4236 with no resolution.Workaround proposal 2 - Import the Logger object and create a child.
Here are 2 issues:
getLogger
.typeshed/stdlib/logging
: theregetChild
is defined asHowever, we need something along the lines of
Cf. python/mypy#1212
Beta Was this translation helpful? Give feedback.
All reactions