Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion mypy/checker_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,9 @@ def visit_typeddict_index_expr(
raise NotImplementedError

@abstractmethod
def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type:
def infer_literal_expr_type(
self, value: LiteralValue, fallback_name: str, context: Context
) -> Type:
raise NotImplementedError

@abstractmethod
Expand Down
30 changes: 17 additions & 13 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,9 @@ def analyze_var_ref(self, var: Var, context: Context) -> Type:
if self.is_literal_context() and var_type.last_known_value is not None:
return var_type.last_known_value
if var.name in {"True", "False"}:
return self.infer_literal_expr_type(var.name == "True", "builtins.bool")
return self.infer_literal_expr_type(
var.name == "True", "builtins.bool", context
)
return var.type
else:
if not var.is_ready and self.chk.in_checked_function():
Expand Down Expand Up @@ -3503,7 +3505,9 @@ def analyze_external_member_access(
def is_literal_context(self) -> bool:
return is_literal_type_like(self.type_context[-1])

def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type:
def infer_literal_expr_type(
self, value: LiteralValue, fallback_name: str, context: Context
) -> Type:
"""Analyzes the given literal expression and determines if we should be
inferring an Instance type, a Literal[...] type, or an Instance that
remembers the original literal. We...
Expand All @@ -3521,22 +3525,22 @@ def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Ty
the comments in Instance's constructor for more details.
"""
typ = self.named_type(fallback_name)
typ.set_line(context)
literal_typ = LiteralType(
value=value, fallback=typ, line=context.line, column=context.column
)
if self.is_literal_context():
return LiteralType(value=value, fallback=typ)
return literal_typ
else:
if value is True:
if self._literal_true is None:
self._literal_true = typ.copy_modified(
last_known_value=LiteralType(value=value, fallback=typ)
)
self._literal_true = typ.copy_modified(last_known_value=literal_typ)
return self._literal_true
if value is False:
if self._literal_false is None:
self._literal_false = typ.copy_modified(
last_known_value=LiteralType(value=value, fallback=typ)
)
self._literal_false = typ.copy_modified(last_known_value=literal_typ)
return self._literal_false
return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ))
return typ.copy_modified(last_known_value=literal_typ)

def concat_tuples(self, left: TupleType, right: TupleType) -> TupleType:
"""Concatenate two fixed length tuples."""
Expand All @@ -3547,15 +3551,15 @@ def concat_tuples(self, left: TupleType, right: TupleType) -> TupleType:

def visit_int_expr(self, e: IntExpr) -> Type:
"""Type check an integer literal (trivial)."""
return self.infer_literal_expr_type(e.value, "builtins.int")
return self.infer_literal_expr_type(e.value, "builtins.int", e)

def visit_str_expr(self, e: StrExpr) -> Type:
"""Type check a string literal (trivial)."""
return self.infer_literal_expr_type(e.value, "builtins.str")
return self.infer_literal_expr_type(e.value, "builtins.str", e)

def visit_bytes_expr(self, e: BytesExpr) -> Type:
"""Type check a bytes literal (trivial)."""
return self.infer_literal_expr_type(e.value, "builtins.bytes")
return self.infer_literal_expr_type(e.value, "builtins.bytes", e)

def visit_float_expr(self, e: FloatExpr) -> Type:
"""Type check a float literal (trivial)."""
Expand Down
2 changes: 1 addition & 1 deletion mypy/checkpattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def visit_singleton_pattern(self, o: SingletonPattern) -> PatternType:
current_type = self.type_context[-1]
value: bool | None = o.value
if isinstance(value, bool):
typ = self.chk.expr_checker.infer_literal_expr_type(value, "builtins.bool")
typ = self.chk.expr_checker.infer_literal_expr_type(value, "builtins.bool", o)
elif value is None:
typ = NoneType()
else:
Expand Down
18 changes: 18 additions & 0 deletions test-data/unit/check-columns.test
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,24 @@ if int():
if int():
reveal_type(1) # N:17: Revealed type is "Literal[1]?"

[case testColumnLiteralExprTypeContext]
# flags: --config-file tmp/mypy.ini
def print_literal_context(x: object) -> None: ...

print_literal_context(1)
print_literal_context("x")
print_literal_context(True)
print_literal_context(False)

[file mypy.ini]
\[mypy]
plugins=<ROOT>/test-data/unit/plugins/literal_context.py
[out]
main:4:23: note: literal type Literal[1]? has line and column context
main:5:23: note: literal type Literal['x']? has line and column context
main:6:23: note: literal type Literal[True]? has line and column context
main:7:23: note: literal type Literal[False]? has line and column context

[case testColumnNonOverlappingEqualityCheck]
# flags: --strict-equality
if 1 == '': # E:4: Non-overlapping equality check (left operand type: "Literal[1]", right operand type: "Literal['']")
Expand Down
21 changes: 21 additions & 0 deletions test-data/unit/plugins/literal_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from collections.abc import Callable

from mypy.plugin import FunctionContext, Plugin
from mypy.types import Type


class LiteralContextPlugin(Plugin):
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
if fullname == "__main__.print_literal_context":
return report_literal_type_context
return None


def report_literal_type_context(ctx: FunctionContext) -> Type:
typ = ctx.arg_types[0][0]
ctx.api.msg.note(f"literal type {typ} has line and column context", typ)
return ctx.default_return_type


def plugin(version: str) -> type[LiteralContextPlugin]:
return LiteralContextPlugin
Loading