Type Hints
Loguru relies on a stub file to document its types. This implies that these types are not
accessible during execution of your program, however they can be used by type checkers and IDE.
Also, this means that your Python interpreter has to support postponed evaluation of annotations
to prevent error at runtime. This is achieved with a __future__ import in Python 3.7+ or by using
string literals for earlier versions.
A basic usage example could look like this:
from __future__ import annotations
import loguru
from loguru import logger
def good_sink(message: loguru.Message):
print("My name is", message.record["name"])
def bad_filter(record: loguru.Record):
return record["invalid"]
logger.add(good_sink, filter=bad_filter)
$ mypy test.py
test.py:8: error: TypedDict "Record" has no key 'invalid'
Found 1 error in 1 file (checked 1 source file)
There are several internal types to which you can be exposed using Loguru’s public API, they are listed here and might be useful to type hint your code:
Logger: the usualLoggerobject (also returned byopt(),bind()andpatch()).Message: the formatted logging message sent to the sinks (astrwithrecordattribute).Record: thedictcontaining all contextual information of the logged message.Level: thenamedtuplereturned bylevel()(withname,no,colorandiconattributes).Catcher: the context decorator returned bycatch().Contextualizer: the context decorator returned bycontextualize().AwaitableCompleter: the awaitable object returned bycomplete().RecordFile: therecord["file"]withnameandpathattributes.RecordLevel: therecord["level"]withname,noandiconattributes.RecordThread: therecord["thread"]withidandnameattributes.RecordProcess: therecord["process"]withidandnameattributes.RecordException: therecord["exception"]withtype,valueandtracebackattributes.
If that is not enough, one can also use the loguru-mypy library developed by @kornicameister.
Plugin can be installed separately using:
pip install loguru-mypy
It helps to catch several possible runtime errors by performing additional checks like:
opt(lazy=True)loggers accepting onlytyping.Callable[[], typing.Any]argumentsopt(record=True)loggers wrongly calling log handler like sologger.info(..., record={})and even more…
For more details, go to official documentation of loguru-mypy.
See also: Source Code of Type Hints.