mohi666 mohi666 - 1 year ago 101
Python Question

Logging handler namer annotations in mypy

I'm trying to annotate my logging module using mypy in Python 3, however, I'm having issues annotating the namer function:

import logging

def _namer(name: str) -> str:
return name + '.gz'

def get_logger(file_name: str, level: str) -> logging.Logger:
logger = logging.getLogger(__name__)
handler = TimedRotatingFileHandler(file_name, backupCount=30, when='midnight')

handler.namer = _namer
return logger


When I run mypy, I get this error when I assign _namer to handler.namer:

error: Incompatible types in assignment (expression has type Callable[[str], str], variable has type "Optional[Callable[[str], None]]")


Any idea how I'm supposed annotate _namer so that mypy doesn't complain about it?

Answer Source

It appears that this is a bug in mypy! Or more accurately, this is a bug in Typeshed, a compendium of type stubs for various libraries used by different type checkers, including mypy.

After looking through the documentation and the source code of logging.handler, it does seem that the type of the handler.namer attribute should be Optional[Callable[[str], str]], which matches your code.

However, if we check typeshed, we can see it's given a type of Optional[Callable[[str], None]]. This seems like a simple oversight to me.

I would recommend making pull request with a fix at the typeshed repo. Until then, you can silence mypy by adding the # type: ignore comment to that line with the assignment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download