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

What is the recommended way to 'type hint' a loguru logger being passed around or returned by a function? #1110

Open
epicwhale opened this issue Mar 27, 2024 · 4 comments
Labels
question Further information is requested

Comments

@epicwhale
Copy link

Wondering, how do you typehint a logger being passed around in code?

def my_function(a, ctx_logger: ????):
     ctx_logger.debug(...)

I tried using :Logger by importing from loguru import Logger but it gives me a "ImportError: cannot import name 'Logger' from 'loguru'" error

Couldn't find a clear answer here either: https://stackoverflow.com/questions/66411218/type-hint-for-returning-loguru-logger

@epicwhale
Copy link
Author

the only workaround I figured so far is:

from loguru import logger

Logger = type(logger)

def process_data(data: str, logger: Logger) -> None:
    ...

@changchiyou
Copy link

  1. Improvement of your workaround:

    from ._logger import Logger as _Logger

    image

  2. (Recommand) Please refer to https://loguru.readthedocs.io/en/stable/api/type_hints.html# :

    image

@epicwhale
Copy link
Author

good shout, the from loguru._logger import Logger approach seems like the least ugliest of the lot :)

@Delgan
Copy link
Owner

Delgan commented Mar 30, 2024

Actually, you should preferably not use from loguru._logger import Logger. This is an internal type that is not supposed to be exposed publicly. You'll also miss many of the other types listed in the documentation: Type hints.

You're facing ImportError because the Loguru types being defined in a stub file, they're only accessible to type checkers, not at run-time.

See this answer for more details: #1101 (comment)

The following solution should work fine:

import loguru

def my_function(a, ctx_logger: "loguru.Logger"):
     ctx_logger.debug(...)

Alternatively:

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from loguru import Logger

def my_function(a, ctx_logger: Logger):
     ctx_logger.debug(...)

@Delgan Delgan added the question Further information is requested label Mar 30, 2024
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

3 participants