Ejemplo n.º 1
0
 def visit_JoinedStr(self, n: ast3.JoinedStr) -> Expression:
     result_expression = StrExpr('')  # type: Expression
     for value_expr in self.translate_expr_list(n.values):
         string_method = MemberExpr(value_expr, '__str__')
         string_method.set_line(value_expr)
         stringified_value_expr = CallExpr(string_method, [], [])
         stringified_value_expr.set_line(value_expr)
         result_expression = OpExpr('+', result_expression,
                                    stringified_value_expr)
         result_expression.set_line(value_expr)
     return result_expression
Ejemplo n.º 2
0
def _check_str_format_call(
    log_msg_expr: t.Union[StrExpr, NameExpr],
    ctx: MethodContext,
) -> None:
    """ Taps into mypy to typecheck something like this:

        ```py
        logger.debug('The bar is "{my_foo.bar}"', my_foo=foo)
        ```

        as if it was written like this:

        ```py
        logger.debug('The bar is "{my_foo.bar}"'.format(my_foo=foo))
        ```
    """
    call_expr = CallExpr(
        callee=MemberExpr(expr=log_msg_expr, name='format'),
        args=ctx.args[1] + ctx.args[2],
        arg_kinds=ctx.arg_kinds[1] + ctx.arg_kinds[2],
        arg_names=ctx.arg_names[1] + ctx.arg_names[2],
    )
    call_expr.set_line(log_msg_expr)

    # WARNING: `ctx.api` *is* technically a `mypy.checker.TypeChecker` so the cast is
    # safe to make, however, mypy says this should be an implementation detail.
    # So, anything that's not part of the `CheckerPluginInterface` should be expected to
    # change. See https://github.com/python/mypy/issues/6617
    try:
        type_checker = t.cast(TypeChecker, ctx.api)
        type_checker.expr_checker.visit_call_expr(call_expr)
    except AttributeError:
        ctx.api.msg.fail(
            ("AttributeError when trying to access mypy's functionality. "
             'This could mean you are trying to use incompatible versions '
             'of mypy and loguru-mypy.'),
            context=log_msg_expr,
        )