Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type and definition mismatch for Logger class #1101

Open
ukalwa opened this issue Mar 4, 2024 · 1 comment
Open

Type and definition mismatch for Logger class #1101

ukalwa opened this issue Mar 4, 2024 · 1 comment
Labels
question Further information is requested

Comments

@ukalwa
Copy link

ukalwa commented Mar 4, 2024

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

@Delgan
Copy link
Owner

Delgan commented Mar 30, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants