Skip to content
Draft
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
21 changes: 12 additions & 9 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def __init__(self) -> None:
)
from mypy.expandtype import expand_type
from mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash
from mypy.lookup import lookup_core_types_class
from mypy.maptype import map_instance_to_supertype
from mypy.meet import is_overlapping_types, meet_types
from mypy.message_registry import ErrorMessage
Expand Down Expand Up @@ -882,7 +883,7 @@ def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
arg_kinds=[ARG_POS, ARG_POS],
arg_names=[None, None],
ret_type=any_type,
fallback=self.named_type("builtins.function"),
fallback=self.named_type("types.FunctionType"),
)
if setter_type and not is_subtype(setter_type, fallback_setter_type):
self.fail("Invalid property setter signature", defn.setter.func)
Expand Down Expand Up @@ -951,7 +952,7 @@ def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
arg_kinds=[ARG_POS],
arg_names=[None],
ret_type=any_type,
fallback=self.named_type("builtins.function"),
fallback=self.named_type("types.FunctionType"),
)
defn.type = Overloaded([var_type])
# Check override validity after we analyzed current definition.
Expand Down Expand Up @@ -2022,7 +2023,7 @@ def check_reverse_op_method(
[nodes.ARG_POS, nodes.ARG_POS],
[None, None],
AnyType(TypeOfAny.special_form),
self.named_type("builtins.function"),
self.named_type("types.FunctionType"),
)
if not is_subtype(reverse_type, method_type):
self.msg.invalid_signature(reverse_type, context)
Expand Down Expand Up @@ -2248,15 +2249,15 @@ def check_getattr_method(self, typ: Type, context: Context, name: str) -> None:
[nodes.ARG_POS],
[None],
AnyType(TypeOfAny.special_form),
self.named_type("builtins.function"),
self.named_type("types.FunctionType"),
)
elif self.scope.active_class():
method_type = CallableType(
[AnyType(TypeOfAny.special_form), self.named_type("builtins.str")],
[nodes.ARG_POS, nodes.ARG_POS],
[None, None],
AnyType(TypeOfAny.special_form),
self.named_type("builtins.function"),
self.named_type("types.FunctionType"),
)
else:
return
Expand All @@ -2275,7 +2276,7 @@ def check_setattr_method(self, typ: Type, context: Context) -> None:
[nodes.ARG_POS, nodes.ARG_POS, nodes.ARG_POS],
[None, None, None],
NoneType(),
self.named_type("builtins.function"),
self.named_type("types.FunctionType"),
)
if not is_subtype(typ, method_type):
self.msg.invalid_signature_for_special_method(typ, context, "__setattr__")
Expand Down Expand Up @@ -6446,7 +6447,7 @@ def intersect_instance_callable(self, typ: Instance, callable_type: CallableType
def make_fake_callable(self, typ: Instance) -> Instance:
"""Produce a new type that makes type Callable with a generic callable type."""

fallback = self.named_type("builtins.function")
fallback = self.named_type("types.FunctionType")
callable_type = CallableType(
[AnyType(TypeOfAny.explicit), AnyType(TypeOfAny.explicit)],
[nodes.ARG_STAR, nodes.ARG_STAR2],
Expand Down Expand Up @@ -7977,7 +7978,7 @@ def named_type(self, name: str) -> Instance:
if instance_cache.str_type is None:
instance_cache.str_type = self._named_type(name)
return instance_cache.str_type
if name == "builtins.function":
if name == "types.FunctionType":
if instance_cache.function_type is None:
instance_cache.function_type = self._named_type(name)
return instance_cache.function_type
Expand Down Expand Up @@ -8084,6 +8085,8 @@ def lookup_qualified(self, name: str) -> SymbolTableNode:
if "." not in name:
return self.lookup(name)
else:
if (sym := lookup_core_types_class(name, self.modules)) is not None:
return sym
parts = name.split(".")
n = self.modules[parts[0]]
for i in range(1, len(parts) - 1):
Expand Down Expand Up @@ -8259,7 +8262,7 @@ def iterable_item_type(self, it: ProperType, context: Context) -> Type:
return self.analyze_iterable_item_type_without_expression(it, context)[1]

def function_type(self, func: FuncBase) -> FunctionLike:
typ = function_type(func, self.named_type("builtins.function"))
typ = function_type(func, self.named_type("types.FunctionType"))
if (
isinstance(func, FuncItem)
and func.is_coroutine
Expand Down
18 changes: 9 additions & 9 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) ->
e.callee.arg_kinds,
e.callee.arg_names,
ret_type=self.object_type(),
fallback=self.named_type("builtins.function"),
fallback=self.named_type("types.FunctionType"),
)
callee_type = get_proper_type(
self.accept(e.callee, type_context, always_allow_any=True, is_callee=True)
Expand Down Expand Up @@ -2053,7 +2053,7 @@ def analyze_type_type_callee(self, item: ProperType, context: Context) -> Type:
arg_kinds=[],
arg_names=[],
ret_type=NoneType(),
fallback=self.named_type("builtins.function"),
fallback=self.named_type("types.FunctionType"),
name=None,
from_type_type=True,
)
Expand Down Expand Up @@ -3983,7 +3983,7 @@ def visit_comparison_expr(self, e: ComparisonExpr) -> Type:
[nodes.ARG_POS],
[None],
self.bool_type(),
self.named_type("builtins.function"),
self.named_type("types.FunctionType"),
)
e.method_types.append(method_type)
iterable_types.append(itertype)
Expand Down Expand Up @@ -5475,7 +5475,7 @@ def check_lst_expr(self, e: ListExpr | SetExpr | TupleExpr, fullname: str, tag:
[nodes.ARG_STAR],
[None],
self.chk.named_generic_type(fullname, [tv]),
self.named_type("builtins.function"),
self.named_type("types.FunctionType"),
name=tag,
variables=[tv],
)
Expand Down Expand Up @@ -5767,7 +5767,7 @@ def _visit_dict_expr(self, e: DictExpr) -> Type:
[nodes.ARG_POS] * len(expected_types),
[None] * len(expected_types),
self.chk.named_generic_type("builtins.dict", [kt, vt]),
self.named_type("builtins.function"),
self.named_type("types.FunctionType"),
name="<dict>",
variables=[kt, vt],
)
Expand Down Expand Up @@ -5842,7 +5842,7 @@ def visit_lambda_expr(self, e: LambdaExpr) -> Type:
# Only type check the return expression, not the return statement.
# There's no useful type context.
ret_type = self.accept(e.expr(), allow_none_return=True)
fallback = self.named_type("builtins.function")
fallback = self.named_type("types.FunctionType")
self.chk.return_types.pop()
self.in_lambda_expr = old_in_lambda
return callable_type(e, fallback, ret_type)
Expand Down Expand Up @@ -5905,7 +5905,7 @@ def infer_lambda_type_using_context(

# The callable_ctx may have a fallback of builtins.type if the context
# is a constructor -- but this fallback doesn't make sense for lambdas.
callable_ctx = callable_ctx.copy_modified(fallback=self.named_type("builtins.function"))
callable_ctx = callable_ctx.copy_modified(fallback=self.named_type("types.FunctionType"))

if callable_ctx.type_guard is not None or callable_ctx.type_is is not None:
# Lambda's return type cannot be treated as a `TypeGuard`,
Expand Down Expand Up @@ -6185,7 +6185,7 @@ def check_generator_or_comprehension(
[nodes.ARG_POS],
[None],
self.chk.named_generic_type(type_name, tv_list + additional_args),
self.chk.named_type("builtins.function"),
self.chk.named_type("types.FunctionType"),
name=id_for_messages,
variables=[tv],
)
Expand Down Expand Up @@ -6240,7 +6240,7 @@ def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type:
arg_kinds,
arg_names,
self.chk.named_generic_type("builtins.dict", [ktdef, vtdef]),
self.chk.named_type("builtins.function"),
self.chk.named_type("types.FunctionType"),
name="<dictionary-comprehension>",
variables=[ktdef, vtdef],
)
Expand Down
6 changes: 3 additions & 3 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ def analyze_none_member_access(name: str, typ: NoneType, mx: MemberContext) -> T
arg_kinds=[],
arg_names=[],
ret_type=literal_false,
fallback=mx.named_type("builtins.function"),
fallback=mx.named_type("types.FunctionType"),
)
else:
return _analyze_member_access(name, mx.named_type("builtins.object"), mx)
Expand Down Expand Up @@ -1401,7 +1401,7 @@ def analyze_typeddict_access(
arg_kinds=[ARG_POS, ARG_POS],
arg_names=[None, None],
ret_type=NoneType(),
fallback=mx.chk.named_type("builtins.function"),
fallback=mx.chk.named_type("types.FunctionType"),
name=name,
)
elif name == "__delitem__":
Expand All @@ -1410,7 +1410,7 @@ def analyze_typeddict_access(
arg_kinds=[ARG_POS],
arg_names=[None],
ret_type=NoneType(),
fallback=mx.chk.named_type("builtins.function"),
fallback=mx.chk.named_type("types.FunctionType"),
name=name,
)
return _analyze_member_access(name, typ.fallback, mx, override_info)
Expand Down
2 changes: 1 addition & 1 deletion mypy/checkpattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,7 +733,7 @@ def get_class_pattern_type_ranges(self, typ: Type, o: ClassPattern) -> list[Type
and o.class_ref.node.fullname == "typing.Callable"
):
# Create a `Callable[..., Any]`
fallback = self.chk.named_type("builtins.function")
fallback = self.chk.named_type("types.FunctionType")
any_type = AnyType(TypeOfAny.unannotated)
typ = callable_with_ellipsis(any_type, ret_type=any_type, fallback=fallback)
return [TypeRange(typ, is_upper_bound=False)]
Expand Down
5 changes: 4 additions & 1 deletion mypy/fixup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from typing import Any, Final

from mypy.lookup import lookup_fully_qualified
from mypy.lookup import lookup_core_types_class, lookup_fully_qualified
from mypy.nodes import (
Block,
ClassDef,
Expand Down Expand Up @@ -374,6 +374,9 @@ def visit_type_type(self, t: TypeType) -> None:
def lookup_fully_qualified_typeinfo(
modules: dict[str, MypyFile], name: str, *, allow_missing: bool
) -> TypeInfo:
if (stnode := lookup_core_types_class(name, modules)) is not None:
assert isinstance(stnode.node, TypeInfo)
return stnode.node
stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)
node = stnode.node if stnode else None
if isinstance(node, TypeInfo):
Expand Down
9 changes: 5 additions & 4 deletions mypy/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -836,11 +836,12 @@ def join_similar_callables(t: CallableType, s: CallableType) -> CallableType:
arg_types.append(safe_meet(t.arg_types[i], s.arg_types[i]))
# TODO Handle more kinds and different argument names.
# TODO what should happen if one fallback is 'type' and the other is a custom metaclass?
# The fallback type can be either 'function', 'type', or some user-provided metaclass.
# The result should always use 'function' as a fallback if either operands are using it.
if t.fallback.type.fullname == "builtins.function":
# The fallback type can be either 'types.FunctionType', 'type', or some user-provided
# metaclass. The result should always use 'types.FunctionType' as a fallback if either
# operand is using it.
if t.fallback.type.fullname == "types.FunctionType":
fallback = t.fallback
elif s.fallback.type.fullname == "builtins.function":
elif s.fallback.type.fullname == "types.FunctionType":
fallback = s.fallback
else:
fallback = InstanceJoiner().join_instances(t.fallback, s.fallback)
Expand Down
49 changes: 48 additions & 1 deletion mypy/lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,57 @@

from __future__ import annotations

from mypy.nodes import MypyFile, SymbolTableNode, TypeInfo
from collections.abc import Callable
from typing import Final

from mypy.mro import calculate_mro
from mypy.nodes import GDEF, Block, ClassDef, MypyFile, SymbolTable, SymbolTableNode, TypeInfo
from mypy.types import Instance

# TODO: gradually move existing lookup functions to this module.

# Special cased classes from the 'types' module that are needed for basic functionality.
CORE_TYPES_CLASSES: Final = ["FunctionType"]


def make_placeholder_types_info(
name: str, obj_type: Callable[[], Instance] | None = None
) -> TypeInfo:
"""Create a placeholder TypeInfo for a core class of the 'types' module.

The placeholders will be replaced by the real definitions if the 'types'
module is loaded, but they are needed to make the core classes resolvable
even when it isn't (e.g. in tests using minimal builtins fixtures).
"""
cdef = ClassDef(name, Block([])) # Dummy ClassDef, will be replaced later
info = TypeInfo(SymbolTable(), cdef, "types")
info._fullname = f"types.{name}"
calculate_mro(info, obj_type)
return info


def lookup_core_types_class(fullname: str, modules: dict[str, MypyFile]) -> SymbolTableNode | None:
"""Return a placeholder symbol for a missing core class of the 'types' module.

The 'types' module may not be loaded (e.g. in tests using minimal builtins
fixtures), but core classes such as 'types.FunctionType' must be resolvable
for basic functionality.
"""
module, _, name = fullname.rpartition(".")
if module != "types" or name not in CORE_TYPES_CLASSES:
return None
mod = modules.get(module)
if mod is not None and name in mod.names:
return None
obj_type: Callable[[], Instance] | None = None
builtins = modules.get("builtins")
if builtins is not None:
sym = builtins.names.get("object")
if sym is not None and isinstance(sym.node, TypeInfo):
object_info = sym.node
obj_type = lambda: Instance(object_info, [])
return SymbolTableNode(GDEF, make_placeholder_types_info(name, obj_type))


def lookup_fully_qualified(
name: str, modules: dict[str, MypyFile], *, raise_on_missing: bool = False
Expand Down
6 changes: 3 additions & 3 deletions mypy/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -1246,9 +1246,9 @@ def meet_similar_callables(t: CallableType, s: CallableType) -> CallableType:
for i in range(len(t.arg_types)):
arg_types.append(safe_join(t.arg_types[i], s.arg_types[i]))
# TODOs in join_similar_callables() also applies here.
# The fallback type can be either 'function' or 'type'. The result should have 'function' as
# fallback only if both operands have it as 'function'.
if t.fallback.type.fullname != "builtins.function":
# The fallback type can be either 'types.FunctionType' or 'type'. The result should have
# 'types.FunctionType' as fallback only if both operands have it as 'types.FunctionType'.
if t.fallback.type.fullname != "types.FunctionType":
fallback = t.fallback
else:
fallback = s.fallback
Expand Down
2 changes: 1 addition & 1 deletion mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ def has_no_attr(
return codes.INDEX
elif member == "__call__":
if isinstance(original_type, Instance) and (
original_type.type.fullname == "builtins.function"
original_type.type.fullname == "types.FunctionType"
):
# "'function' not callable" is a confusing error message.
# Explain that the problem is that the type of the function is not known.
Expand Down
4 changes: 2 additions & 2 deletions mypy/plugins/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,9 @@ def _add_method_by_spec(
), "Can't add a new method that's both staticmethod and classmethod."

if isinstance(api, SemanticAnalyzerPluginInterface):
function_type = api.named_type("builtins.function")
function_type = api.named_type("types.FunctionType")
else:
function_type = api.named_generic_type("builtins.function", [])
function_type = api.named_generic_type("types.FunctionType", [])

if is_classmethod:
self_type = self_type or TypeType(fill_typevars(info))
Expand Down
16 changes: 7 additions & 9 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
from mypy.errorcodes import PROPERTY_DECORATOR, ErrorCode
from mypy.errors import Errors, report_internal_error
from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type
from mypy.lookup import lookup_core_types_class
from mypy.message_registry import CANNOT_DECLARE_TYPE_OF_SPECIAL_FORM, ErrorMessage
from mypy.messages import (
SUGGESTED_TEST_FIXTURES,
Expand Down Expand Up @@ -346,7 +347,7 @@

# Special cased built-in classes that are needed for basic functionality and need to be
# available very early on.
CORE_BUILTIN_CLASSES: Final = ["object", "bool", "function"]
CORE_BUILTIN_CLASSES: Final = ["object", "bool"]


# Python has several different scope/namespace kinds with subtly different semantics.
Expand Down Expand Up @@ -2581,12 +2582,8 @@ def prepare_class_def(self, defn: ClassDef, info: TypeInfo | None = None) -> Non
self.add_global_symbol(defn.name, defn, defn.info)

def make_empty_type_info(self, defn: ClassDef) -> TypeInfo:
if (
self.is_module_scope()
and self.cur_mod_id == "builtins"
and defn.name in CORE_BUILTIN_CLASSES
):
# Special case core built-in classes. A TypeInfo was already
if self.is_module_scope() and self.is_core_builtin_class(defn):
# Special case core classes. A TypeInfo was already
# created for it before semantic analysis, but with a dummy
# ClassDef. Patch the real ClassDef object.
info = self.globals[defn.name].node
Expand Down Expand Up @@ -7061,7 +7058,8 @@ def lookup_fully_qualified_or_none(self, fullname: str) -> SymbolTableNode | Non
"""
# TODO: unify/clean-up/simplify lookup methods, see #4157.
module, name = fullname.rsplit(".", maxsplit=1)

if (sym := lookup_core_types_class(fullname, self.modules)) is not None:
return sym
if module in self.modules:
# If the module exists, look up the name in the module.
# This is the common case.
Expand Down Expand Up @@ -7113,7 +7111,7 @@ def str_type(self) -> Instance:

def function_type(self) -> Instance:
if self._function_type is None:
self._function_type = self.named_type("builtins.function")
self._function_type = self.named_type("types.FunctionType")
return self._function_type

def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance:
Expand Down
Loading
Loading