Delgan / loguru

Python logging made (stupidly) simple

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Type and definition mismatch for Logger class

ukalwa opened this issue · comments

When I am importing and using Logger class (for typing purposes) as shown below, I am getting an import error like ImportError: cannot import name 'Logger' from 'loguru'.

from loguru import Logger, logger

def setup_logger(_logger: Logger) -> Logger:
    ...

Turns out it is imported as _Logger in __init__.py and thereby a mismatch between type and definition.

from ._logger import Logger as _Logger

Hi @ukalwa.

Loguru references type hints through a stub file only. The types are not accessible at run-time, they only exist in the context of type checkers execution.

You should use postponed evaluation of type hints, either using strings:

import loguru

def setup_logger(_logger: "loguru.Logger") -> "loguru.Logger":
    ...

Or using a __future__ from PEP 563:

from __future__ import annotations

def setup_logger(_logger: loguru.Logger) -> loguru.Logger:
    ...

If you want to import only specific types, you can also rely on the TYPE_CHECKING variable:

from __future__ import annotations
import typing

if typing.TYPE_CHECKING:
    from loguru import Logger

def setup_logger(_logger: Logger) -> Logger:
    ...

See Loguru documentation: Type hints.