Skip to content

Commit

Permalink
Accept variables (NameExpr) in loguru calls
Browse files Browse the repository at this point in the history
Partially fixes kornicameister#49

Note that mypy _cannot_ type-check a format expression if it is not Final.
E.g.:

```python
from loguru import logger
from typing import Final

foo: Final = "bar"
logger.info(foo, 1)  # error: Not all arguments converted during string formatting
foo = "bar"
logger.info(foo, 1)  # no error (and will fail at runtime)
```

This is a limitation with mypy and I don't think we can do much about it
  • Loading branch information
ThibaultLemaire committed Jan 4, 2021
1 parent c176016 commit 9f268ea
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
7 changes: 5 additions & 2 deletions loguru_mypy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ class Opts(t.NamedTuple):
} # type: te.Final


def _check_str_format_call(log_msg_expr: StrExpr, ctx: MethodContext) -> None:
def _check_str_format_call(
log_msg_expr: t.Union[StrExpr, NameExpr],
ctx: MethodContext,
) -> None:
""" Taps into mypy to typecheck something like this:
```py
Expand Down Expand Up @@ -98,7 +101,7 @@ def _loguru_logger_call_handler(
log_msg_expr = ctx.args[0][0]
logger_opts = loggers.get(ctx.type) or DEFAULT_OPTS

if isinstance(log_msg_expr, StrExpr):
if isinstance(log_msg_expr, (StrExpr, NameExpr)):
_check_str_format_call(log_msg_expr, ctx)
elif isinstance(log_msg_expr, (IntExpr, FloatExpr)):
# nothing to be done, this is valid log
Expand Down
32 changes: 32 additions & 0 deletions typesafety/test_issue_49.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,35 @@
logger.debug(123.3)
logger.trace(1)
logger.error(.3)
- case: variables
main: |
from loguru import logger
foo = "bar"
logger.info(foo)
logger.debug(foo)
logger.trace(foo)
logger.error(foo)
- case: variables__type-checked__wrong
main: |
from loguru import logger
from typing import Final
foo: Final = "bar"
logger.info(foo, 1)
out: |
main:5: error: Not all arguments converted during string formatting [str-format]
- case: variables__type-checked__correct
main: |
from loguru import logger
from typing import Final
foo: Final = "bar {}"
logger.info(foo, 1)
- case: variables__mypy_cant_tell
main: |
from loguru import logger
from typing import Final
foo = "bar"
logger.info(foo, 1) # This is wrong but mypy is at a loss

0 comments on commit 9f268ea

Please sign in to comment.