Search code examples
pythonloggingpython-typing

Type hint for returning loguru logger


Does anyone know the proper type hint for returning a loguru logger? Using loguru.Logger passes mypy checks, but when the function get_logger is called I get the error AttributeError: module 'loguru' has no attribute 'Logger'

import copy
from pathlib import Path
from sys import stdout

from loguru import logger
import loguru


def get_logger(log_path: Path) -> loguru.Logger:
    logger.remove()
    logger_ = copy.deepcopy(logger)
    logger_.add(stdout)
    logger_.add(f"{log_path}.log")

    return logger_


Solution

  • I learned that loguru.Logger is correct and can be used without throwing an error if from __future__ import annotations is added to the list of imports.

    This comes from the loguru type hint documentation

    Example:

    from __future__ import annotations
    
    import loguru
    
    def get_logger(
        colorize: bool = True,
        serialize: bool = False,
        file_format: str = LOG_FORMAT_SIMPLE,
    ) -> loguru.Logger: