checkmember.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. """Type checking of attribute access"""
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING, Callable, Sequence, cast
  4. from mypy import meet, message_registry, subtypes
  5. from mypy.erasetype import erase_typevars
  6. from mypy.expandtype import (
  7. expand_self_type,
  8. expand_type_by_instance,
  9. freshen_all_functions_type_vars,
  10. )
  11. from mypy.maptype import map_instance_to_supertype
  12. from mypy.messages import MessageBuilder
  13. from mypy.nodes import (
  14. ARG_POS,
  15. ARG_STAR,
  16. ARG_STAR2,
  17. SYMBOL_FUNCBASE_TYPES,
  18. Context,
  19. Decorator,
  20. FuncBase,
  21. FuncDef,
  22. IndexExpr,
  23. MypyFile,
  24. OverloadedFuncDef,
  25. SymbolNode,
  26. SymbolTable,
  27. TempNode,
  28. TypeAlias,
  29. TypeInfo,
  30. TypeVarExpr,
  31. Var,
  32. is_final_node,
  33. )
  34. from mypy.plugin import AttributeContext
  35. from mypy.typeops import (
  36. bind_self,
  37. class_callable,
  38. erase_to_bound,
  39. function_type,
  40. get_type_vars,
  41. make_simplified_union,
  42. supported_self_type,
  43. tuple_fallback,
  44. type_object_type_from_function,
  45. )
  46. from mypy.types import (
  47. ENUM_REMOVED_PROPS,
  48. AnyType,
  49. CallableType,
  50. DeletedType,
  51. FunctionLike,
  52. Instance,
  53. LiteralType,
  54. NoneType,
  55. Overloaded,
  56. ParamSpecType,
  57. PartialType,
  58. ProperType,
  59. TupleType,
  60. Type,
  61. TypedDictType,
  62. TypeOfAny,
  63. TypeType,
  64. TypeVarLikeType,
  65. TypeVarTupleType,
  66. TypeVarType,
  67. UnionType,
  68. get_proper_type,
  69. )
  70. from mypy.typetraverser import TypeTraverserVisitor
  71. if TYPE_CHECKING: # import for forward declaration only
  72. import mypy.checker
  73. from mypy import state
  74. class MemberContext:
  75. """Information and objects needed to type check attribute access.
  76. Look at the docstring of analyze_member_access for more information.
  77. """
  78. def __init__(
  79. self,
  80. is_lvalue: bool,
  81. is_super: bool,
  82. is_operator: bool,
  83. original_type: Type,
  84. context: Context,
  85. msg: MessageBuilder,
  86. chk: mypy.checker.TypeChecker,
  87. self_type: Type | None,
  88. module_symbol_table: SymbolTable | None = None,
  89. no_deferral: bool = False,
  90. is_self: bool = False,
  91. ) -> None:
  92. self.is_lvalue = is_lvalue
  93. self.is_super = is_super
  94. self.is_operator = is_operator
  95. self.original_type = original_type
  96. self.self_type = self_type or original_type
  97. self.context = context # Error context
  98. self.msg = msg
  99. self.chk = chk
  100. self.module_symbol_table = module_symbol_table
  101. self.no_deferral = no_deferral
  102. self.is_self = is_self
  103. def named_type(self, name: str) -> Instance:
  104. return self.chk.named_type(name)
  105. def not_ready_callback(self, name: str, context: Context) -> None:
  106. self.chk.handle_cannot_determine_type(name, context)
  107. def copy_modified(
  108. self,
  109. *,
  110. messages: MessageBuilder | None = None,
  111. self_type: Type | None = None,
  112. is_lvalue: bool | None = None,
  113. ) -> MemberContext:
  114. mx = MemberContext(
  115. self.is_lvalue,
  116. self.is_super,
  117. self.is_operator,
  118. self.original_type,
  119. self.context,
  120. self.msg,
  121. self.chk,
  122. self.self_type,
  123. self.module_symbol_table,
  124. self.no_deferral,
  125. )
  126. if messages is not None:
  127. mx.msg = messages
  128. if self_type is not None:
  129. mx.self_type = self_type
  130. if is_lvalue is not None:
  131. mx.is_lvalue = is_lvalue
  132. return mx
  133. def analyze_member_access(
  134. name: str,
  135. typ: Type,
  136. context: Context,
  137. is_lvalue: bool,
  138. is_super: bool,
  139. is_operator: bool,
  140. msg: MessageBuilder,
  141. *,
  142. original_type: Type,
  143. chk: mypy.checker.TypeChecker,
  144. override_info: TypeInfo | None = None,
  145. in_literal_context: bool = False,
  146. self_type: Type | None = None,
  147. module_symbol_table: SymbolTable | None = None,
  148. no_deferral: bool = False,
  149. is_self: bool = False,
  150. ) -> Type:
  151. """Return the type of attribute 'name' of 'typ'.
  152. The actual implementation is in '_analyze_member_access' and this docstring
  153. also applies to it.
  154. This is a general operation that supports various different variations:
  155. 1. lvalue or non-lvalue access (setter or getter access)
  156. 2. supertype access when using super() (is_super == True and
  157. 'override_info' should refer to the supertype)
  158. 'original_type' is the most precise inferred or declared type of the base object
  159. that we have available. When looking for an attribute of 'typ', we may perform
  160. recursive calls targeting the fallback type, and 'typ' may become some supertype
  161. of 'original_type'. 'original_type' is always preserved as the 'typ' type used in
  162. the initial, non-recursive call. The 'self_type' is a component of 'original_type'
  163. to which generic self should be bound (a narrower type that has a fallback to instance).
  164. Currently this is used only for union types.
  165. 'module_symbol_table' is passed to this function if 'typ' is actually a module
  166. and we want to keep track of the available attributes of the module (since they
  167. are not available via the type object directly)
  168. """
  169. mx = MemberContext(
  170. is_lvalue,
  171. is_super,
  172. is_operator,
  173. original_type,
  174. context,
  175. msg,
  176. chk=chk,
  177. self_type=self_type,
  178. module_symbol_table=module_symbol_table,
  179. no_deferral=no_deferral,
  180. is_self=is_self,
  181. )
  182. result = _analyze_member_access(name, typ, mx, override_info)
  183. possible_literal = get_proper_type(result)
  184. if (
  185. in_literal_context
  186. and isinstance(possible_literal, Instance)
  187. and possible_literal.last_known_value is not None
  188. ):
  189. return possible_literal.last_known_value
  190. else:
  191. return result
  192. def _analyze_member_access(
  193. name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None
  194. ) -> Type:
  195. # TODO: This and following functions share some logic with subtypes.find_member;
  196. # consider refactoring.
  197. typ = get_proper_type(typ)
  198. if isinstance(typ, Instance):
  199. return analyze_instance_member_access(name, typ, mx, override_info)
  200. elif isinstance(typ, AnyType):
  201. # The base object has dynamic type.
  202. return AnyType(TypeOfAny.from_another_any, source_any=typ)
  203. elif isinstance(typ, UnionType):
  204. return analyze_union_member_access(name, typ, mx)
  205. elif isinstance(typ, FunctionLike) and typ.is_type_obj():
  206. return analyze_type_callable_member_access(name, typ, mx)
  207. elif isinstance(typ, TypeType):
  208. return analyze_type_type_member_access(name, typ, mx, override_info)
  209. elif isinstance(typ, TupleType):
  210. # Actually look up from the fallback instance type.
  211. return _analyze_member_access(name, tuple_fallback(typ), mx, override_info)
  212. elif isinstance(typ, (LiteralType, FunctionLike)):
  213. # Actually look up from the fallback instance type.
  214. return _analyze_member_access(name, typ.fallback, mx, override_info)
  215. elif isinstance(typ, TypedDictType):
  216. return analyze_typeddict_access(name, typ, mx, override_info)
  217. elif isinstance(typ, NoneType):
  218. return analyze_none_member_access(name, typ, mx)
  219. elif isinstance(typ, TypeVarLikeType):
  220. if isinstance(typ, TypeVarType) and typ.values:
  221. return _analyze_member_access(
  222. name, make_simplified_union(typ.values), mx, override_info
  223. )
  224. return _analyze_member_access(name, typ.upper_bound, mx, override_info)
  225. elif isinstance(typ, DeletedType):
  226. mx.msg.deleted_as_rvalue(typ, mx.context)
  227. return AnyType(TypeOfAny.from_error)
  228. return report_missing_attribute(mx.original_type, typ, name, mx)
  229. def may_be_awaitable_attribute(
  230. name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None
  231. ) -> bool:
  232. """Check if the given type has the attribute when awaited."""
  233. if mx.chk.checking_missing_await:
  234. # Avoid infinite recursion.
  235. return False
  236. with mx.chk.checking_await_set(), mx.msg.filter_errors() as local_errors:
  237. aw_type = mx.chk.get_precise_awaitable_type(typ, local_errors)
  238. if aw_type is None:
  239. return False
  240. _ = _analyze_member_access(name, aw_type, mx, override_info)
  241. return not local_errors.has_new_errors()
  242. def report_missing_attribute(
  243. original_type: Type,
  244. typ: Type,
  245. name: str,
  246. mx: MemberContext,
  247. override_info: TypeInfo | None = None,
  248. ) -> Type:
  249. res_type = mx.msg.has_no_attr(original_type, typ, name, mx.context, mx.module_symbol_table)
  250. if not mx.msg.prefer_simple_messages():
  251. if may_be_awaitable_attribute(name, typ, mx, override_info):
  252. mx.msg.possible_missing_await(mx.context)
  253. return res_type
  254. # The several functions that follow implement analyze_member_access for various
  255. # types and aren't documented individually.
  256. def analyze_instance_member_access(
  257. name: str, typ: Instance, mx: MemberContext, override_info: TypeInfo | None
  258. ) -> Type:
  259. if name == "__init__" and not mx.is_super:
  260. # Accessing __init__ in statically typed code would compromise
  261. # type safety unless used via super().
  262. mx.msg.fail(message_registry.CANNOT_ACCESS_INIT, mx.context)
  263. return AnyType(TypeOfAny.from_error)
  264. # The base object has an instance type.
  265. info = typ.type
  266. if override_info:
  267. info = override_info
  268. if (
  269. state.find_occurrences
  270. and info.name == state.find_occurrences[0]
  271. and name == state.find_occurrences[1]
  272. ):
  273. mx.msg.note("Occurrence of '{}.{}'".format(*state.find_occurrences), mx.context)
  274. # Look up the member. First look up the method dictionary.
  275. method = info.get_method(name)
  276. if method and not isinstance(method, Decorator):
  277. if mx.is_super:
  278. validate_super_call(method, mx)
  279. if method.is_property:
  280. assert isinstance(method, OverloadedFuncDef)
  281. first_item = method.items[0]
  282. assert isinstance(first_item, Decorator)
  283. return analyze_var(name, first_item.var, typ, info, mx)
  284. if mx.is_lvalue:
  285. mx.msg.cant_assign_to_method(mx.context)
  286. signature = function_type(method, mx.named_type("builtins.function"))
  287. signature = freshen_all_functions_type_vars(signature)
  288. if not method.is_static:
  289. if name != "__call__":
  290. # TODO: use proper treatment of special methods on unions instead
  291. # of this hack here and below (i.e. mx.self_type).
  292. dispatched_type = meet.meet_types(mx.original_type, typ)
  293. signature = check_self_arg(
  294. signature, dispatched_type, method.is_class, mx.context, name, mx.msg
  295. )
  296. signature = bind_self(signature, mx.self_type, is_classmethod=method.is_class)
  297. # TODO: should we skip these steps for static methods as well?
  298. # Since generic static methods should not be allowed.
  299. typ = map_instance_to_supertype(typ, method.info)
  300. member_type = expand_type_by_instance(signature, typ)
  301. freeze_all_type_vars(member_type)
  302. return member_type
  303. else:
  304. # Not a method.
  305. return analyze_member_var_access(name, typ, info, mx)
  306. def validate_super_call(node: FuncBase, mx: MemberContext) -> None:
  307. unsafe_super = False
  308. if isinstance(node, FuncDef) and node.is_trivial_body:
  309. unsafe_super = True
  310. impl = node
  311. elif isinstance(node, OverloadedFuncDef):
  312. if node.impl:
  313. impl = node.impl if isinstance(node.impl, FuncDef) else node.impl.func
  314. unsafe_super = impl.is_trivial_body
  315. if unsafe_super:
  316. ret_type = (
  317. impl.type.ret_type
  318. if isinstance(impl.type, CallableType)
  319. else AnyType(TypeOfAny.unannotated)
  320. )
  321. if not subtypes.is_subtype(NoneType(), ret_type):
  322. mx.msg.unsafe_super(node.name, node.info.name, mx.context)
  323. def analyze_type_callable_member_access(name: str, typ: FunctionLike, mx: MemberContext) -> Type:
  324. # Class attribute.
  325. # TODO super?
  326. ret_type = typ.items[0].ret_type
  327. assert isinstance(ret_type, ProperType)
  328. if isinstance(ret_type, TupleType):
  329. ret_type = tuple_fallback(ret_type)
  330. if isinstance(ret_type, TypedDictType):
  331. ret_type = ret_type.fallback
  332. if isinstance(ret_type, Instance):
  333. if not mx.is_operator:
  334. # When Python sees an operator (eg `3 == 4`), it automatically translates that
  335. # into something like `int.__eq__(3, 4)` instead of `(3).__eq__(4)` as an
  336. # optimization.
  337. #
  338. # While it normally it doesn't matter which of the two versions are used, it
  339. # does cause inconsistencies when working with classes. For example, translating
  340. # `int == int` to `int.__eq__(int)` would not work since `int.__eq__` is meant to
  341. # compare two int _instances_. What we really want is `type(int).__eq__`, which
  342. # is meant to compare two types or classes.
  343. #
  344. # This check makes sure that when we encounter an operator, we skip looking up
  345. # the corresponding method in the current instance to avoid this edge case.
  346. # See https://github.com/python/mypy/pull/1787 for more info.
  347. # TODO: do not rely on same type variables being present in all constructor overloads.
  348. result = analyze_class_attribute_access(
  349. ret_type, name, mx, original_vars=typ.items[0].variables, mcs_fallback=typ.fallback
  350. )
  351. if result:
  352. return result
  353. # Look up from the 'type' type.
  354. return _analyze_member_access(name, typ.fallback, mx)
  355. else:
  356. assert False, f"Unexpected type {ret_type!r}"
  357. def analyze_type_type_member_access(
  358. name: str, typ: TypeType, mx: MemberContext, override_info: TypeInfo | None
  359. ) -> Type:
  360. # Similar to analyze_type_callable_attribute_access.
  361. item = None
  362. fallback = mx.named_type("builtins.type")
  363. if isinstance(typ.item, Instance):
  364. item = typ.item
  365. elif isinstance(typ.item, AnyType):
  366. with mx.msg.filter_errors():
  367. return _analyze_member_access(name, fallback, mx, override_info)
  368. elif isinstance(typ.item, TypeVarType):
  369. upper_bound = get_proper_type(typ.item.upper_bound)
  370. if isinstance(upper_bound, Instance):
  371. item = upper_bound
  372. elif isinstance(upper_bound, UnionType):
  373. return _analyze_member_access(
  374. name,
  375. TypeType.make_normalized(upper_bound, line=typ.line, column=typ.column),
  376. mx,
  377. override_info,
  378. )
  379. elif isinstance(upper_bound, TupleType):
  380. item = tuple_fallback(upper_bound)
  381. elif isinstance(upper_bound, AnyType):
  382. with mx.msg.filter_errors():
  383. return _analyze_member_access(name, fallback, mx, override_info)
  384. elif isinstance(typ.item, TupleType):
  385. item = tuple_fallback(typ.item)
  386. elif isinstance(typ.item, FunctionLike) and typ.item.is_type_obj():
  387. item = typ.item.fallback
  388. elif isinstance(typ.item, TypeType):
  389. # Access member on metaclass object via Type[Type[C]]
  390. if isinstance(typ.item.item, Instance):
  391. item = typ.item.item.type.metaclass_type
  392. ignore_messages = False
  393. if item is not None:
  394. fallback = item.type.metaclass_type or fallback
  395. if item and not mx.is_operator:
  396. # See comment above for why operators are skipped
  397. result = analyze_class_attribute_access(
  398. item, name, mx, mcs_fallback=fallback, override_info=override_info
  399. )
  400. if result:
  401. if not (isinstance(get_proper_type(result), AnyType) and item.type.fallback_to_any):
  402. return result
  403. else:
  404. # We don't want errors on metaclass lookup for classes with Any fallback
  405. ignore_messages = True
  406. with mx.msg.filter_errors(filter_errors=ignore_messages):
  407. return _analyze_member_access(name, fallback, mx, override_info)
  408. def analyze_union_member_access(name: str, typ: UnionType, mx: MemberContext) -> Type:
  409. with mx.msg.disable_type_names():
  410. results = []
  411. for subtype in typ.relevant_items():
  412. # Self types should be bound to every individual item of a union.
  413. item_mx = mx.copy_modified(self_type=subtype)
  414. results.append(_analyze_member_access(name, subtype, item_mx))
  415. return make_simplified_union(results)
  416. def analyze_none_member_access(name: str, typ: NoneType, mx: MemberContext) -> Type:
  417. if name == "__bool__":
  418. literal_false = LiteralType(False, fallback=mx.named_type("builtins.bool"))
  419. return CallableType(
  420. arg_types=[],
  421. arg_kinds=[],
  422. arg_names=[],
  423. ret_type=literal_false,
  424. fallback=mx.named_type("builtins.function"),
  425. )
  426. else:
  427. return _analyze_member_access(name, mx.named_type("builtins.object"), mx)
  428. def analyze_member_var_access(
  429. name: str, itype: Instance, info: TypeInfo, mx: MemberContext
  430. ) -> Type:
  431. """Analyse attribute access that does not target a method.
  432. This is logically part of analyze_member_access and the arguments are similar.
  433. original_type is the type of E in the expression E.var
  434. """
  435. # It was not a method. Try looking up a variable.
  436. v = lookup_member_var_or_accessor(info, name, mx.is_lvalue)
  437. vv = v
  438. if isinstance(vv, Decorator):
  439. # The associated Var node of a decorator contains the type.
  440. v = vv.var
  441. if mx.is_super:
  442. validate_super_call(vv.func, mx)
  443. if isinstance(vv, TypeInfo):
  444. # If the associated variable is a TypeInfo synthesize a Var node for
  445. # the purposes of type checking. This enables us to type check things
  446. # like accessing class attributes on an inner class.
  447. v = Var(name, type=type_object_type(vv, mx.named_type))
  448. v.info = info
  449. if isinstance(vv, TypeAlias):
  450. # Similar to the above TypeInfo case, we allow using
  451. # qualified type aliases in runtime context if it refers to an
  452. # instance type. For example:
  453. # class C:
  454. # A = List[int]
  455. # x = C.A() <- this is OK
  456. typ = mx.chk.expr_checker.alias_type_in_runtime_context(
  457. vv, ctx=mx.context, alias_definition=mx.is_lvalue
  458. )
  459. v = Var(name, type=typ)
  460. v.info = info
  461. if isinstance(v, Var):
  462. implicit = info[name].implicit
  463. # An assignment to final attribute is always an error,
  464. # independently of types.
  465. if mx.is_lvalue and not mx.chk.get_final_context():
  466. check_final_member(name, info, mx.msg, mx.context)
  467. return analyze_var(name, v, itype, info, mx, implicit=implicit)
  468. elif isinstance(v, FuncDef):
  469. assert False, "Did not expect a function"
  470. elif isinstance(v, MypyFile):
  471. mx.chk.module_refs.add(v.fullname)
  472. return mx.chk.expr_checker.module_type(v)
  473. elif (
  474. not v
  475. and name not in ["__getattr__", "__setattr__", "__getattribute__"]
  476. and not mx.is_operator
  477. and mx.module_symbol_table is None
  478. ):
  479. # Above we skip ModuleType.__getattr__ etc. if we have a
  480. # module symbol table, since the symbol table allows precise
  481. # checking.
  482. if not mx.is_lvalue:
  483. for method_name in ("__getattribute__", "__getattr__"):
  484. method = info.get_method(method_name)
  485. # __getattribute__ is defined on builtins.object and returns Any, so without
  486. # the guard this search will always find object.__getattribute__ and conclude
  487. # that the attribute exists
  488. if method and method.info.fullname != "builtins.object":
  489. bound_method = analyze_decorator_or_funcbase_access(
  490. defn=method,
  491. itype=itype,
  492. info=info,
  493. self_type=mx.self_type,
  494. name=method_name,
  495. mx=mx,
  496. )
  497. typ = map_instance_to_supertype(itype, method.info)
  498. getattr_type = get_proper_type(expand_type_by_instance(bound_method, typ))
  499. if isinstance(getattr_type, CallableType):
  500. result = getattr_type.ret_type
  501. else:
  502. result = getattr_type
  503. # Call the attribute hook before returning.
  504. fullname = f"{method.info.fullname}.{name}"
  505. hook = mx.chk.plugin.get_attribute_hook(fullname)
  506. if hook:
  507. result = hook(
  508. AttributeContext(
  509. get_proper_type(mx.original_type), result, mx.context, mx.chk
  510. )
  511. )
  512. return result
  513. else:
  514. setattr_meth = info.get_method("__setattr__")
  515. if setattr_meth and setattr_meth.info.fullname != "builtins.object":
  516. bound_type = analyze_decorator_or_funcbase_access(
  517. defn=setattr_meth,
  518. itype=itype,
  519. info=info,
  520. self_type=mx.self_type,
  521. name=name,
  522. mx=mx.copy_modified(is_lvalue=False),
  523. )
  524. typ = map_instance_to_supertype(itype, setattr_meth.info)
  525. setattr_type = get_proper_type(expand_type_by_instance(bound_type, typ))
  526. if isinstance(setattr_type, CallableType) and len(setattr_type.arg_types) > 0:
  527. return setattr_type.arg_types[-1]
  528. if itype.type.fallback_to_any:
  529. return AnyType(TypeOfAny.special_form)
  530. # Could not find the member.
  531. if itype.extra_attrs and name in itype.extra_attrs.attrs:
  532. # For modules use direct symbol table lookup.
  533. if not itype.extra_attrs.mod_name:
  534. return itype.extra_attrs.attrs[name]
  535. if mx.is_super:
  536. mx.msg.undefined_in_superclass(name, mx.context)
  537. return AnyType(TypeOfAny.from_error)
  538. else:
  539. return report_missing_attribute(mx.original_type, itype, name, mx)
  540. def check_final_member(name: str, info: TypeInfo, msg: MessageBuilder, ctx: Context) -> None:
  541. """Give an error if the name being assigned was declared as final."""
  542. for base in info.mro:
  543. sym = base.names.get(name)
  544. if sym and is_final_node(sym.node):
  545. msg.cant_assign_to_final(name, attr_assign=True, ctx=ctx)
  546. def analyze_descriptor_access(descriptor_type: Type, mx: MemberContext) -> Type:
  547. """Type check descriptor access.
  548. Arguments:
  549. descriptor_type: The type of the descriptor attribute being accessed
  550. (the type of ``f`` in ``a.f`` when ``f`` is a descriptor).
  551. mx: The current member access context.
  552. Return:
  553. The return type of the appropriate ``__get__`` overload for the descriptor.
  554. """
  555. instance_type = get_proper_type(mx.original_type)
  556. orig_descriptor_type = descriptor_type
  557. descriptor_type = get_proper_type(descriptor_type)
  558. if isinstance(descriptor_type, UnionType):
  559. # Map the access over union types
  560. return make_simplified_union(
  561. [analyze_descriptor_access(typ, mx) for typ in descriptor_type.items]
  562. )
  563. elif not isinstance(descriptor_type, Instance):
  564. return orig_descriptor_type
  565. if not descriptor_type.type.has_readable_member("__get__"):
  566. return orig_descriptor_type
  567. dunder_get = descriptor_type.type.get_method("__get__")
  568. if dunder_get is None:
  569. mx.msg.fail(
  570. message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(
  571. descriptor_type.str_with_options(mx.msg.options)
  572. ),
  573. mx.context,
  574. )
  575. return AnyType(TypeOfAny.from_error)
  576. bound_method = analyze_decorator_or_funcbase_access(
  577. defn=dunder_get,
  578. itype=descriptor_type,
  579. info=descriptor_type.type,
  580. self_type=descriptor_type,
  581. name="__get__",
  582. mx=mx,
  583. )
  584. typ = map_instance_to_supertype(descriptor_type, dunder_get.info)
  585. dunder_get_type = expand_type_by_instance(bound_method, typ)
  586. if isinstance(instance_type, FunctionLike) and instance_type.is_type_obj():
  587. owner_type = instance_type.items[0].ret_type
  588. instance_type = NoneType()
  589. elif isinstance(instance_type, TypeType):
  590. owner_type = instance_type.item
  591. instance_type = NoneType()
  592. else:
  593. owner_type = instance_type
  594. callable_name = mx.chk.expr_checker.method_fullname(descriptor_type, "__get__")
  595. dunder_get_type = mx.chk.expr_checker.transform_callee_type(
  596. callable_name,
  597. dunder_get_type,
  598. [
  599. TempNode(instance_type, context=mx.context),
  600. TempNode(TypeType.make_normalized(owner_type), context=mx.context),
  601. ],
  602. [ARG_POS, ARG_POS],
  603. mx.context,
  604. object_type=descriptor_type,
  605. )
  606. _, inferred_dunder_get_type = mx.chk.expr_checker.check_call(
  607. dunder_get_type,
  608. [
  609. TempNode(instance_type, context=mx.context),
  610. TempNode(TypeType.make_normalized(owner_type), context=mx.context),
  611. ],
  612. [ARG_POS, ARG_POS],
  613. mx.context,
  614. object_type=descriptor_type,
  615. callable_name=callable_name,
  616. )
  617. inferred_dunder_get_type = get_proper_type(inferred_dunder_get_type)
  618. if isinstance(inferred_dunder_get_type, AnyType):
  619. # check_call failed, and will have reported an error
  620. return inferred_dunder_get_type
  621. if not isinstance(inferred_dunder_get_type, CallableType):
  622. mx.msg.fail(
  623. message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(
  624. descriptor_type.str_with_options(mx.msg.options)
  625. ),
  626. mx.context,
  627. )
  628. return AnyType(TypeOfAny.from_error)
  629. return inferred_dunder_get_type.ret_type
  630. def is_instance_var(var: Var) -> bool:
  631. """Return if var is an instance variable according to PEP 526."""
  632. return (
  633. # check the type_info node is the var (not a decorated function, etc.)
  634. var.name in var.info.names
  635. and var.info.names[var.name].node is var
  636. and not var.is_classvar
  637. # variables without annotations are treated as classvar
  638. and not var.is_inferred
  639. )
  640. def analyze_var(
  641. name: str,
  642. var: Var,
  643. itype: Instance,
  644. info: TypeInfo,
  645. mx: MemberContext,
  646. *,
  647. implicit: bool = False,
  648. ) -> Type:
  649. """Analyze access to an attribute via a Var node.
  650. This is conceptually part of analyze_member_access and the arguments are similar.
  651. itype is the instance type in which attribute should be looked up
  652. original_type is the type of E in the expression E.var
  653. if implicit is True, the original Var was created as an assignment to self
  654. """
  655. # Found a member variable.
  656. original_itype = itype
  657. itype = map_instance_to_supertype(itype, var.info)
  658. typ = var.type
  659. if typ:
  660. if isinstance(typ, PartialType):
  661. return mx.chk.handle_partial_var_type(typ, mx.is_lvalue, var, mx.context)
  662. if mx.is_lvalue and var.is_property and not var.is_settable_property:
  663. # TODO allow setting attributes in subclass (although it is probably an error)
  664. mx.msg.read_only_property(name, itype.type, mx.context)
  665. if mx.is_lvalue and var.is_classvar:
  666. mx.msg.cant_assign_to_classvar(name, mx.context)
  667. t = freshen_all_functions_type_vars(typ)
  668. if not (mx.is_self or mx.is_super) or supported_self_type(
  669. get_proper_type(mx.original_type)
  670. ):
  671. t = expand_self_type(var, t, mx.original_type)
  672. elif (
  673. mx.is_self
  674. and original_itype.type != var.info
  675. # If an attribute with Self-type was defined in a supertype, we need to
  676. # rebind the Self type variable to Self type variable of current class...
  677. and original_itype.type.self_type is not None
  678. # ...unless `self` has an explicit non-trivial annotation.
  679. and original_itype == mx.chk.scope.active_self_type()
  680. ):
  681. t = expand_self_type(var, t, original_itype.type.self_type)
  682. t = get_proper_type(expand_type_by_instance(t, itype))
  683. freeze_all_type_vars(t)
  684. result: Type = t
  685. typ = get_proper_type(typ)
  686. if (
  687. var.is_initialized_in_class
  688. and (not is_instance_var(var) or mx.is_operator)
  689. and isinstance(typ, FunctionLike)
  690. and not typ.is_type_obj()
  691. ):
  692. if mx.is_lvalue:
  693. if var.is_property:
  694. if not var.is_settable_property:
  695. mx.msg.read_only_property(name, itype.type, mx.context)
  696. else:
  697. mx.msg.cant_assign_to_method(mx.context)
  698. if not var.is_staticmethod:
  699. # Class-level function objects and classmethods become bound methods:
  700. # the former to the instance, the latter to the class.
  701. functype = typ
  702. # Use meet to narrow original_type to the dispatched type.
  703. # For example, assume
  704. # * A.f: Callable[[A1], None] where A1 <: A (maybe A1 == A)
  705. # * B.f: Callable[[B1], None] where B1 <: B (maybe B1 == B)
  706. # * x: Union[A1, B1]
  707. # In `x.f`, when checking `x` against A1 we assume x is compatible with A
  708. # and similarly for B1 when checking against B
  709. dispatched_type = meet.meet_types(mx.original_type, itype)
  710. signature = freshen_all_functions_type_vars(functype)
  711. bound = get_proper_type(expand_self_type(var, signature, mx.original_type))
  712. assert isinstance(bound, FunctionLike)
  713. signature = bound
  714. signature = check_self_arg(
  715. signature, dispatched_type, var.is_classmethod, mx.context, name, mx.msg
  716. )
  717. signature = bind_self(signature, mx.self_type, var.is_classmethod)
  718. expanded_signature = expand_type_by_instance(signature, itype)
  719. freeze_all_type_vars(expanded_signature)
  720. if var.is_property:
  721. # A property cannot have an overloaded type => the cast is fine.
  722. assert isinstance(expanded_signature, CallableType)
  723. result = expanded_signature.ret_type
  724. else:
  725. result = expanded_signature
  726. else:
  727. if not var.is_ready and not mx.no_deferral:
  728. mx.not_ready_callback(var.name, mx.context)
  729. # Implicit 'Any' type.
  730. result = AnyType(TypeOfAny.special_form)
  731. fullname = f"{var.info.fullname}.{name}"
  732. hook = mx.chk.plugin.get_attribute_hook(fullname)
  733. if result and not mx.is_lvalue and not implicit:
  734. result = analyze_descriptor_access(result, mx)
  735. if hook:
  736. result = hook(
  737. AttributeContext(get_proper_type(mx.original_type), result, mx.context, mx.chk)
  738. )
  739. return result
  740. def freeze_all_type_vars(member_type: Type) -> None:
  741. member_type.accept(FreezeTypeVarsVisitor())
  742. class FreezeTypeVarsVisitor(TypeTraverserVisitor):
  743. def visit_callable_type(self, t: CallableType) -> None:
  744. for v in t.variables:
  745. v.id.meta_level = 0
  746. super().visit_callable_type(t)
  747. def lookup_member_var_or_accessor(info: TypeInfo, name: str, is_lvalue: bool) -> SymbolNode | None:
  748. """Find the attribute/accessor node that refers to a member of a type."""
  749. # TODO handle lvalues
  750. node = info.get(name)
  751. if node:
  752. return node.node
  753. else:
  754. return None
  755. def check_self_arg(
  756. functype: FunctionLike,
  757. dispatched_arg_type: Type,
  758. is_classmethod: bool,
  759. context: Context,
  760. name: str,
  761. msg: MessageBuilder,
  762. ) -> FunctionLike:
  763. """Check that an instance has a valid type for a method with annotated 'self'.
  764. For example if the method is defined as:
  765. class A:
  766. def f(self: S) -> T: ...
  767. then for 'x.f' we check that meet(type(x), A) <: S. If the method is overloaded, we
  768. select only overloads items that satisfy this requirement. If there are no matching
  769. overloads, an error is generated.
  770. Note: dispatched_arg_type uses a meet to select a relevant item in case if the
  771. original type of 'x' is a union. This is done because several special methods
  772. treat union types in ad-hoc manner, so we can't use MemberContext.self_type yet.
  773. """
  774. items = functype.items
  775. if not items:
  776. return functype
  777. new_items = []
  778. if is_classmethod:
  779. dispatched_arg_type = TypeType.make_normalized(dispatched_arg_type)
  780. for item in items:
  781. if not item.arg_types or item.arg_kinds[0] not in (ARG_POS, ARG_STAR):
  782. # No positional first (self) argument (*args is okay).
  783. msg.no_formal_self(name, item, context)
  784. # This is pretty bad, so just return the original signature if
  785. # there is at least one such error.
  786. return functype
  787. else:
  788. selfarg = get_proper_type(item.arg_types[0])
  789. if subtypes.is_subtype(dispatched_arg_type, erase_typevars(erase_to_bound(selfarg))):
  790. new_items.append(item)
  791. elif isinstance(selfarg, ParamSpecType):
  792. # TODO: This is not always right. What's the most reasonable thing to do here?
  793. new_items.append(item)
  794. elif isinstance(selfarg, TypeVarTupleType):
  795. raise NotImplementedError
  796. if not new_items:
  797. # Choose first item for the message (it may be not very helpful for overloads).
  798. msg.incompatible_self_argument(
  799. name, dispatched_arg_type, items[0], is_classmethod, context
  800. )
  801. return functype
  802. if len(new_items) == 1:
  803. return new_items[0]
  804. return Overloaded(new_items)
  805. def analyze_class_attribute_access(
  806. itype: Instance,
  807. name: str,
  808. mx: MemberContext,
  809. *,
  810. mcs_fallback: Instance,
  811. override_info: TypeInfo | None = None,
  812. original_vars: Sequence[TypeVarLikeType] | None = None,
  813. ) -> Type | None:
  814. """Analyze access to an attribute on a class object.
  815. itype is the return type of the class object callable, original_type is the type
  816. of E in the expression E.var, original_vars are type variables of the class callable
  817. (for generic classes).
  818. """
  819. info = itype.type
  820. if override_info:
  821. info = override_info
  822. fullname = f"{info.fullname}.{name}"
  823. hook = mx.chk.plugin.get_class_attribute_hook(fullname)
  824. node = info.get(name)
  825. if not node:
  826. if itype.extra_attrs and name in itype.extra_attrs.attrs:
  827. # For modules use direct symbol table lookup.
  828. if not itype.extra_attrs.mod_name:
  829. return itype.extra_attrs.attrs[name]
  830. if info.fallback_to_any or info.meta_fallback_to_any:
  831. return apply_class_attr_hook(mx, hook, AnyType(TypeOfAny.special_form))
  832. return None
  833. if (
  834. isinstance(node.node, Var)
  835. and not node.node.is_classvar
  836. and not hook
  837. and mcs_fallback.type.get(name)
  838. ):
  839. # If the same attribute is declared on the metaclass and the class but with different types,
  840. # and the attribute on the class is not a ClassVar,
  841. # the type of the attribute on the metaclass should take priority
  842. # over the type of the attribute on the class,
  843. # when the attribute is being accessed from the class object itself.
  844. #
  845. # Return `None` here to signify that the name should be looked up
  846. # on the class object itself rather than the instance.
  847. return None
  848. is_decorated = isinstance(node.node, Decorator)
  849. is_method = is_decorated or isinstance(node.node, FuncBase)
  850. if mx.is_lvalue:
  851. if is_method:
  852. mx.msg.cant_assign_to_method(mx.context)
  853. if isinstance(node.node, TypeInfo):
  854. mx.msg.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, mx.context)
  855. # Refuse class attribute access if slot defined
  856. if info.slots and name in info.slots:
  857. mx.msg.fail(message_registry.CLASS_VAR_CONFLICTS_SLOTS.format(name), mx.context)
  858. # If a final attribute was declared on `self` in `__init__`, then it
  859. # can't be accessed on the class object.
  860. if node.implicit and isinstance(node.node, Var) and node.node.is_final:
  861. mx.msg.fail(
  862. message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR.format(node.node.name), mx.context
  863. )
  864. # An assignment to final attribute on class object is also always an error,
  865. # independently of types.
  866. if mx.is_lvalue and not mx.chk.get_final_context():
  867. check_final_member(name, info, mx.msg, mx.context)
  868. if info.is_enum and not (mx.is_lvalue or is_decorated or is_method):
  869. enum_class_attribute_type = analyze_enum_class_attribute_access(itype, name, mx)
  870. if enum_class_attribute_type:
  871. return apply_class_attr_hook(mx, hook, enum_class_attribute_type)
  872. t = node.type
  873. if t:
  874. if isinstance(t, PartialType):
  875. symnode = node.node
  876. assert isinstance(symnode, Var)
  877. return apply_class_attr_hook(
  878. mx, hook, mx.chk.handle_partial_var_type(t, mx.is_lvalue, symnode, mx.context)
  879. )
  880. # Find the class where method/variable was defined.
  881. if isinstance(node.node, Decorator):
  882. super_info: TypeInfo | None = node.node.var.info
  883. elif isinstance(node.node, (Var, SYMBOL_FUNCBASE_TYPES)):
  884. super_info = node.node.info
  885. else:
  886. super_info = None
  887. # Map the type to how it would look as a defining class. For example:
  888. # class C(Generic[T]): ...
  889. # class D(C[Tuple[T, S]]): ...
  890. # D[int, str].method()
  891. # Here itype is D[int, str], isuper is C[Tuple[int, str]].
  892. if not super_info:
  893. isuper = None
  894. else:
  895. isuper = map_instance_to_supertype(itype, super_info)
  896. if isinstance(node.node, Var):
  897. assert isuper is not None
  898. # Check if original variable type has type variables. For example:
  899. # class C(Generic[T]):
  900. # x: T
  901. # C.x # Error, ambiguous access
  902. # C[int].x # Also an error, since C[int] is same as C at runtime
  903. # Exception is Self type wrapped in ClassVar, that is safe.
  904. def_vars = set(node.node.info.defn.type_vars)
  905. if not node.node.is_classvar and node.node.info.self_type:
  906. def_vars.add(node.node.info.self_type)
  907. typ_vars = set(get_type_vars(t))
  908. if def_vars & typ_vars:
  909. # Exception: access on Type[...], including first argument of class methods is OK.
  910. if not isinstance(get_proper_type(mx.original_type), TypeType) or node.implicit:
  911. if node.node.is_classvar:
  912. message = message_registry.GENERIC_CLASS_VAR_ACCESS
  913. else:
  914. message = message_registry.GENERIC_INSTANCE_VAR_CLASS_ACCESS
  915. mx.msg.fail(message, mx.context)
  916. # Erase non-mapped variables, but keep mapped ones, even if there is an error.
  917. # In the above example this means that we infer following types:
  918. # C.x -> Any
  919. # C[int].x -> int
  920. t = get_proper_type(expand_self_type(node.node, t, itype))
  921. t = erase_typevars(expand_type_by_instance(t, isuper), {tv.id for tv in def_vars})
  922. is_classmethod = (is_decorated and cast(Decorator, node.node).func.is_class) or (
  923. isinstance(node.node, FuncBase) and node.node.is_class
  924. )
  925. t = get_proper_type(t)
  926. if isinstance(t, FunctionLike) and is_classmethod:
  927. t = check_self_arg(t, mx.self_type, False, mx.context, name, mx.msg)
  928. result = add_class_tvars(
  929. t, isuper, is_classmethod, mx.self_type, original_vars=original_vars
  930. )
  931. if not mx.is_lvalue:
  932. result = analyze_descriptor_access(result, mx)
  933. return apply_class_attr_hook(mx, hook, result)
  934. elif isinstance(node.node, Var):
  935. mx.not_ready_callback(name, mx.context)
  936. return AnyType(TypeOfAny.special_form)
  937. if isinstance(node.node, TypeVarExpr):
  938. mx.msg.fail(
  939. message_registry.CANNOT_USE_TYPEVAR_AS_EXPRESSION.format(info.name, name), mx.context
  940. )
  941. return AnyType(TypeOfAny.from_error)
  942. if isinstance(node.node, TypeInfo):
  943. return type_object_type(node.node, mx.named_type)
  944. if isinstance(node.node, MypyFile):
  945. # Reference to a module object.
  946. return mx.named_type("types.ModuleType")
  947. if isinstance(node.node, TypeAlias):
  948. return mx.chk.expr_checker.alias_type_in_runtime_context(
  949. node.node, ctx=mx.context, alias_definition=mx.is_lvalue
  950. )
  951. if is_decorated:
  952. assert isinstance(node.node, Decorator)
  953. if node.node.type:
  954. return apply_class_attr_hook(mx, hook, node.node.type)
  955. else:
  956. mx.not_ready_callback(name, mx.context)
  957. return AnyType(TypeOfAny.from_error)
  958. else:
  959. assert isinstance(node.node, FuncBase)
  960. typ = function_type(node.node, mx.named_type("builtins.function"))
  961. # Note: if we are accessing class method on class object, the cls argument is bound.
  962. # Annotated and/or explicit class methods go through other code paths above, for
  963. # unannotated implicit class methods we do this here.
  964. if node.node.is_class:
  965. typ = bind_self(typ, is_classmethod=True)
  966. return apply_class_attr_hook(mx, hook, typ)
  967. def apply_class_attr_hook(
  968. mx: MemberContext, hook: Callable[[AttributeContext], Type] | None, result: Type
  969. ) -> Type | None:
  970. if hook:
  971. result = hook(
  972. AttributeContext(get_proper_type(mx.original_type), result, mx.context, mx.chk)
  973. )
  974. return result
  975. def analyze_enum_class_attribute_access(
  976. itype: Instance, name: str, mx: MemberContext
  977. ) -> Type | None:
  978. # Skip these since Enum will remove it
  979. if name in ENUM_REMOVED_PROPS:
  980. return report_missing_attribute(mx.original_type, itype, name, mx)
  981. # For other names surrendered by underscores, we don't make them Enum members
  982. if name.startswith("__") and name.endswith("__") and name.replace("_", "") != "":
  983. return None
  984. enum_literal = LiteralType(name, fallback=itype)
  985. return itype.copy_modified(last_known_value=enum_literal)
  986. def analyze_typeddict_access(
  987. name: str, typ: TypedDictType, mx: MemberContext, override_info: TypeInfo | None
  988. ) -> Type:
  989. if name == "__setitem__":
  990. if isinstance(mx.context, IndexExpr):
  991. # Since we can get this during `a['key'] = ...`
  992. # it is safe to assume that the context is `IndexExpr`.
  993. item_type = mx.chk.expr_checker.visit_typeddict_index_expr(
  994. typ, mx.context.index, setitem=True
  995. )
  996. else:
  997. # It can also be `a.__setitem__(...)` direct call.
  998. # In this case `item_type` can be `Any`,
  999. # because we don't have args available yet.
  1000. # TODO: check in `default` plugin that `__setitem__` is correct.
  1001. item_type = AnyType(TypeOfAny.implementation_artifact)
  1002. return CallableType(
  1003. arg_types=[mx.chk.named_type("builtins.str"), item_type],
  1004. arg_kinds=[ARG_POS, ARG_POS],
  1005. arg_names=[None, None],
  1006. ret_type=NoneType(),
  1007. fallback=mx.chk.named_type("builtins.function"),
  1008. name=name,
  1009. )
  1010. elif name == "__delitem__":
  1011. return CallableType(
  1012. arg_types=[mx.chk.named_type("builtins.str")],
  1013. arg_kinds=[ARG_POS],
  1014. arg_names=[None],
  1015. ret_type=NoneType(),
  1016. fallback=mx.chk.named_type("builtins.function"),
  1017. name=name,
  1018. )
  1019. return _analyze_member_access(name, typ.fallback, mx, override_info)
  1020. def add_class_tvars(
  1021. t: ProperType,
  1022. isuper: Instance | None,
  1023. is_classmethod: bool,
  1024. original_type: Type,
  1025. original_vars: Sequence[TypeVarLikeType] | None = None,
  1026. ) -> Type:
  1027. """Instantiate type variables during analyze_class_attribute_access,
  1028. e.g T and Q in the following:
  1029. class A(Generic[T]):
  1030. @classmethod
  1031. def foo(cls: Type[Q]) -> Tuple[T, Q]: ...
  1032. class B(A[str]): pass
  1033. B.foo()
  1034. Args:
  1035. t: Declared type of the method (or property)
  1036. isuper: Current instance mapped to the superclass where method was defined, this
  1037. is usually done by map_instance_to_supertype()
  1038. is_classmethod: True if this method is decorated with @classmethod
  1039. original_type: The value of the type B in the expression B.foo() or the corresponding
  1040. component in case of a union (this is used to bind the self-types)
  1041. original_vars: Type variables of the class callable on which the method was accessed
  1042. Returns:
  1043. Expanded method type with added type variables (when needed).
  1044. """
  1045. # TODO: verify consistency between Q and T
  1046. # We add class type variables if the class method is accessed on class object
  1047. # without applied type arguments, this matches the behavior of __init__().
  1048. # For example (continuing the example in docstring):
  1049. # A # The type of callable is def [T] () -> A[T], _not_ def () -> A[Any]
  1050. # A[int] # The type of callable is def () -> A[int]
  1051. # and
  1052. # A.foo # The type is generic def [T] () -> Tuple[T, A[T]]
  1053. # A[int].foo # The type is non-generic def () -> Tuple[int, A[int]]
  1054. #
  1055. # This behaviour is useful for defining alternative constructors for generic classes.
  1056. # To achieve such behaviour, we add the class type variables that are still free
  1057. # (i.e. appear in the return type of the class object on which the method was accessed).
  1058. if isinstance(t, CallableType):
  1059. tvars = original_vars if original_vars is not None else []
  1060. if is_classmethod:
  1061. t = freshen_all_functions_type_vars(t)
  1062. t = bind_self(t, original_type, is_classmethod=True)
  1063. assert isuper is not None
  1064. t = expand_type_by_instance(t, isuper)
  1065. freeze_all_type_vars(t)
  1066. return t.copy_modified(variables=list(tvars) + list(t.variables))
  1067. elif isinstance(t, Overloaded):
  1068. return Overloaded(
  1069. [
  1070. cast(
  1071. CallableType,
  1072. add_class_tvars(
  1073. item, isuper, is_classmethod, original_type, original_vars=original_vars
  1074. ),
  1075. )
  1076. for item in t.items
  1077. ]
  1078. )
  1079. if isuper is not None:
  1080. t = expand_type_by_instance(t, isuper)
  1081. return t
  1082. def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> ProperType:
  1083. """Return the type of a type object.
  1084. For a generic type G with type variables T and S the type is generally of form
  1085. Callable[..., G[T, S]]
  1086. where ... are argument types for the __init__/__new__ method (without the self
  1087. argument). Also, the fallback type will be 'type' instead of 'function'.
  1088. """
  1089. # We take the type from whichever of __init__ and __new__ is first
  1090. # in the MRO, preferring __init__ if there is a tie.
  1091. init_method = info.get("__init__")
  1092. new_method = info.get("__new__")
  1093. if not init_method or not is_valid_constructor(init_method.node):
  1094. # Must be an invalid class definition.
  1095. return AnyType(TypeOfAny.from_error)
  1096. # There *should* always be a __new__ method except the test stubs
  1097. # lack it, so just copy init_method in that situation
  1098. new_method = new_method or init_method
  1099. if not is_valid_constructor(new_method.node):
  1100. # Must be an invalid class definition.
  1101. return AnyType(TypeOfAny.from_error)
  1102. # The two is_valid_constructor() checks ensure this.
  1103. assert isinstance(new_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator))
  1104. assert isinstance(init_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator))
  1105. init_index = info.mro.index(init_method.node.info)
  1106. new_index = info.mro.index(new_method.node.info)
  1107. fallback = info.metaclass_type or named_type("builtins.type")
  1108. if init_index < new_index:
  1109. method: FuncBase | Decorator = init_method.node
  1110. is_new = False
  1111. elif init_index > new_index:
  1112. method = new_method.node
  1113. is_new = True
  1114. else:
  1115. if init_method.node.info.fullname == "builtins.object":
  1116. # Both are defined by object. But if we've got a bogus
  1117. # base class, we can't know for sure, so check for that.
  1118. if info.fallback_to_any:
  1119. # Construct a universal callable as the prototype.
  1120. any_type = AnyType(TypeOfAny.special_form)
  1121. sig = CallableType(
  1122. arg_types=[any_type, any_type],
  1123. arg_kinds=[ARG_STAR, ARG_STAR2],
  1124. arg_names=["_args", "_kwds"],
  1125. ret_type=any_type,
  1126. fallback=named_type("builtins.function"),
  1127. )
  1128. return class_callable(sig, info, fallback, None, is_new=False)
  1129. # Otherwise prefer __init__ in a tie. It isn't clear that this
  1130. # is the right thing, but __new__ caused problems with
  1131. # typeshed (#5647).
  1132. method = init_method.node
  1133. is_new = False
  1134. # Construct callable type based on signature of __init__. Adjust
  1135. # return type and insert type arguments.
  1136. if isinstance(method, FuncBase):
  1137. t = function_type(method, fallback)
  1138. else:
  1139. assert isinstance(method.type, ProperType)
  1140. assert isinstance(method.type, FunctionLike) # is_valid_constructor() ensures this
  1141. t = method.type
  1142. return type_object_type_from_function(t, info, method.info, fallback, is_new)
  1143. def analyze_decorator_or_funcbase_access(
  1144. defn: Decorator | FuncBase,
  1145. itype: Instance,
  1146. info: TypeInfo,
  1147. self_type: Type | None,
  1148. name: str,
  1149. mx: MemberContext,
  1150. ) -> Type:
  1151. """Analyzes the type behind method access.
  1152. The function itself can possibly be decorated.
  1153. See: https://github.com/python/mypy/issues/10409
  1154. """
  1155. if isinstance(defn, Decorator):
  1156. return analyze_var(name, defn.var, itype, info, mx)
  1157. return bind_self(
  1158. function_type(defn, mx.chk.named_type("builtins.function")), original_type=self_type
  1159. )
  1160. def is_valid_constructor(n: SymbolNode | None) -> bool:
  1161. """Does this node represents a valid constructor method?
  1162. This includes normal functions, overloaded functions, and decorators
  1163. that return a callable type.
  1164. """
  1165. if isinstance(n, FuncBase):
  1166. return True
  1167. if isinstance(n, Decorator):
  1168. return isinstance(get_proper_type(n.type), FunctionLike)
  1169. return False