1111from collections .abc import Iterable , Sequence
1212from typing import Any , Callable , TypeVar , cast
1313
14+ from mypy .checker_state import checker_state
1415from mypy .copytype import copy_type
1516from mypy .expandtype import expand_type , expand_type_by_instance
1617from mypy .maptype import map_instance_to_supertype
@@ -145,6 +146,15 @@ def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> P
145146 where ... are argument types for the __init__/__new__ method (without the self
146147 argument). Also, the fallback type will be 'type' instead of 'function'.
147148 """
149+ allow_cache = (
150+ checker_state .type_checker is not None
151+ and checker_state .type_checker .allow_constructor_cache
152+ )
153+
154+ if info .type_object_type is not None :
155+ if allow_cache :
156+ return info .type_object_type
157+ info .type_object_type = None
148158
149159 # We take the type from whichever of __init__ and __new__ is first
150160 # in the MRO, preferring __init__ if there is a tie.
@@ -189,7 +199,10 @@ def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> P
189199 is_bound = True ,
190200 fallback = named_type ("builtins.function" ),
191201 )
192- return class_callable (sig , info , fallback , None , is_new = False )
202+ result : FunctionLike = class_callable (sig , info , fallback , None , is_new = False )
203+ if allow_cache :
204+ info .type_object_type = result
205+ return result
193206
194207 # Otherwise prefer __init__ in a tie. It isn't clear that this
195208 # is the right thing, but __new__ caused problems with
@@ -204,7 +217,10 @@ def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> P
204217 assert isinstance (method .type , ProperType )
205218 assert isinstance (method .type , FunctionLike ) # is_valid_constructor() ensures this
206219 t = method .type
207- return type_object_type_from_function (t , info , method .info , fallback , is_new )
220+ result = type_object_type_from_function (t , info , method .info , fallback , is_new )
221+ if allow_cache :
222+ info .type_object_type = result
223+ return result
208224
209225
210226def is_valid_constructor (n : SymbolNode | None ) -> bool :
0 commit comments