I'm trying to annotate my logging module using mypy in Python 3, however, I'm having issues annotating the namer function:
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
error: Incompatible types in assignment (expression has type Callable[[str], str], variable has type "Optional[Callable[[str], None]]")
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.