Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/objects.py: 35%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

164 statements  

1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html 

2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE 

3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt 

4 

5""" 

6Inference objects are a way to represent composite AST nodes, 

7which are used only as inference results, so they can't be found in the 

8original AST tree. For instance, inferring the following frozenset use, 

9leads to an inferred FrozenSet: 

10 

11 Call(func=Name('frozenset'), args=Tuple(...)) 

12""" 

13 

14from __future__ import annotations 

15 

16from collections.abc import Generator, Iterator 

17from functools import cached_property 

18from typing import Literal, NoReturn, Self 

19 

20from astroid import bases, util 

21from astroid.context import InferenceContext 

22from astroid.exceptions import ( 

23 AttributeInferenceError, 

24 InferenceError, 

25 MroError, 

26 SuperError, 

27) 

28from astroid.interpreter import objectmodel 

29from astroid.manager import AstroidManager 

30from astroid.nodes import node_classes, scoped_nodes 

31from astroid.typing import InferenceResult, SuccessfulInferenceResult 

32 

33 

34class FrozenSet(node_classes.BaseContainer): 

35 """Class representing a FrozenSet composite node.""" 

36 

37 def pytype(self) -> Literal["builtins.frozenset"]: 

38 return "builtins.frozenset" 

39 

40 def _infer(self, context: InferenceContext | None = None): 

41 yield self 

42 

43 @cached_property 

44 def _proxied(self): 

45 ast_builtins = AstroidManager().builtins_module 

46 return ast_builtins.getattr("frozenset")[0] 

47 

48 

49class Super(node_classes.NodeNG): 

50 """Proxy class over a super call. 

51 

52 This class offers almost the same behaviour as Python's super, 

53 which is MRO lookups for retrieving attributes from the parents. 

54 

55 The *mro_pointer* is the place in the MRO from where we should 

56 start looking, not counting it. *mro_type* is the object which 

57 provides the MRO, it can be both a type or an instance. 

58 *self_class* is the class where the super call is, while 

59 *scope* is the function where the super call is. 

60 """ 

61 

62 special_attributes = objectmodel.SuperModel() 

63 

64 def __init__( 

65 self, 

66 mro_pointer: SuccessfulInferenceResult, 

67 mro_type: SuccessfulInferenceResult, 

68 self_class: scoped_nodes.ClassDef, 

69 scope: scoped_nodes.FunctionDef, 

70 call: node_classes.Call, 

71 ) -> None: 

72 self.type = mro_type 

73 self.mro_pointer = mro_pointer 

74 self._class_based = False 

75 self._self_class = self_class 

76 self._scope = scope 

77 super().__init__( 

78 parent=scope, 

79 lineno=scope.lineno, 

80 col_offset=scope.col_offset, 

81 end_lineno=scope.end_lineno, 

82 end_col_offset=scope.end_col_offset, 

83 ) 

84 

85 def _infer(self, context: InferenceContext | None = None): 

86 yield self 

87 

88 def super_mro(self): 

89 """Get the MRO which will be used to lookup attributes in this super.""" 

90 if not isinstance(self.mro_pointer, scoped_nodes.ClassDef): 

91 raise SuperError( 

92 "The first argument to super must be a subtype of " 

93 "type, not {mro_pointer}.", 

94 super_=self, 

95 ) 

96 

97 if isinstance(self.type, scoped_nodes.ClassDef): 

98 # `super(type, type)`, most likely in a class method. 

99 self._class_based = True 

100 mro_type = self.type 

101 else: 

102 mro_type = getattr(self.type, "_proxied", None) 

103 if not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef)): 

104 raise SuperError( 

105 "The second argument to super must be an " 

106 "instance or subtype of type, not {type}.", 

107 super_=self, 

108 ) 

109 

110 mro = mro_type.mro() 

111 if self.mro_pointer not in mro: 

112 raise SuperError( 

113 "The second argument to super must be an " 

114 "instance or subtype of type, not {type}.", 

115 super_=self, 

116 ) 

117 

118 index = mro.index(self.mro_pointer) 

119 return mro[index + 1 :] 

120 

121 @cached_property 

122 def _proxied(self): 

123 ast_builtins = AstroidManager().builtins_module 

124 return ast_builtins.getattr("super")[0] 

125 

126 def pytype(self) -> Literal["builtins.super"]: 

127 return "builtins.super" 

128 

129 def display_type(self) -> str: 

130 return "Super of" 

131 

132 @property 

133 def name(self): 

134 """Get the name of the MRO pointer.""" 

135 return self.mro_pointer.name 

136 

137 def qname(self) -> Literal["super"]: 

138 return "super" 

139 

140 def igetattr( # noqa: C901 

141 self, name: str, context: InferenceContext | None = None 

142 ) -> Iterator[InferenceResult]: 

143 """Retrieve the inferred values of the given attribute name.""" 

144 # '__class__' is a special attribute that should be taken directly 

145 # from the special attributes dict 

146 if name == "__class__": 

147 yield self.special_attributes.lookup(name) 

148 return 

149 

150 try: 

151 mro = self.super_mro() 

152 # Don't let invalid MROs or invalid super calls 

153 # leak out as is from this function. 

154 except SuperError as exc: 

155 raise AttributeInferenceError( 

156 ( 

157 "Lookup for {name} on {target!r} because super call {super!r} " 

158 "is invalid." 

159 ), 

160 target=self, 

161 attribute=name, 

162 context=context, 

163 super_=exc.super_, 

164 ) from exc 

165 except MroError as exc: 

166 raise AttributeInferenceError( 

167 ( 

168 "Lookup for {name} on {target!r} failed because {cls!r} has an " 

169 "invalid MRO." 

170 ), 

171 target=self, 

172 attribute=name, 

173 context=context, 

174 mros=exc.mros, 

175 cls=exc.cls, 

176 ) from exc 

177 found = False 

178 for cls in mro: 

179 if name not in cls.locals: 

180 continue 

181 

182 found = True 

183 for inferred in bases._infer_stmts([cls[name]], context, frame=self): 

184 if not isinstance(inferred, scoped_nodes.FunctionDef): 

185 yield inferred 

186 continue 

187 

188 # We can obtain different descriptors from a super depending 

189 # on what we are accessing and where the super call is. 

190 if inferred.type == "classmethod": 

191 # Pass original caller for classmethod too 

192 yield bases.BoundMethod(inferred, cls, original_caller=self.type) 

193 elif self._scope.type == "classmethod" and inferred.type == "method": 

194 yield inferred 

195 elif self._class_based or inferred.type == "staticmethod": 

196 yield inferred 

197 elif isinstance(inferred, Property): 

198 function = inferred.function 

199 try: 

200 yield from function.infer_call_result( 

201 caller=self, context=context 

202 ) 

203 except InferenceError: 

204 yield util.Uninferable 

205 elif bases._is_property(inferred): 

206 # TODO: support other descriptors as well. 

207 try: 

208 yield from inferred.infer_call_result(self, context) 

209 except InferenceError: 

210 yield util.Uninferable 

211 else: 

212 # Pass original caller (self.type) so infer_call_result can 

213 # correctly resolve Self return types to the actual caller type 

214 yield bases.BoundMethod(inferred, cls, original_caller=self.type) 

215 

216 # Only if we haven't found any explicit overwrites for the 

217 # attribute we look it up in the special attributes 

218 if not found and name in self.special_attributes: 

219 special_attr = self.special_attributes.lookup(name) 

220 if not isinstance(special_attr, node_classes.Unknown): 

221 yield special_attr 

222 return 

223 

224 if not found: 

225 raise AttributeInferenceError(target=self, attribute=name, context=context) 

226 

227 def getattr(self, name, context: InferenceContext | None = None): 

228 return list(self.igetattr(name, context=context)) 

229 

230 

231class ExceptionInstance(bases.Instance): 

232 """Class for instances of exceptions. 

233 

234 It has special treatment for some of the exceptions's attributes, 

235 which are transformed at runtime into certain concrete objects, such as 

236 the case of .args. 

237 """ 

238 

239 @cached_property 

240 def special_attributes(self): 

241 qname = self.qname() 

242 instance = objectmodel.BUILTIN_EXCEPTIONS.get( 

243 qname, objectmodel.ExceptionInstanceModel 

244 ) 

245 return instance()(self) 

246 

247 

248class DictInstance(bases.Instance): 

249 """Special kind of instances for dictionaries. 

250 

251 This instance knows the underlying object model of the dictionaries, which means 

252 that methods such as .values or .items can be properly inferred. 

253 """ 

254 

255 special_attributes = objectmodel.DictModel() 

256 

257 

258# Custom objects tailored for dictionary views 

259# returned by dict.items(), dict.keys() and dict.values(). 

260class DictItems(bases.Proxy): 

261 __str__ = node_classes.NodeNG.__str__ 

262 __repr__ = node_classes.NodeNG.__repr__ 

263 

264 

265class DictKeys(bases.Proxy): 

266 __str__ = node_classes.NodeNG.__str__ 

267 __repr__ = node_classes.NodeNG.__repr__ 

268 

269 

270class DictValues(bases.Proxy): 

271 __str__ = node_classes.NodeNG.__str__ 

272 __repr__ = node_classes.NodeNG.__repr__ 

273 

274 

275class PartialFunction(scoped_nodes.FunctionDef): 

276 """A class representing partial function obtained via functools.partial.""" 

277 

278 def __init__( 

279 self, 

280 call=None, 

281 name=None, 

282 lineno=None, 

283 col_offset=None, 

284 parent=None, 

285 *, 

286 end_lineno=None, 

287 end_col_offset=None, 

288 filled_args=None, 

289 filled_keywords=None, 

290 ): 

291 super().__init__( 

292 name, 

293 lineno=lineno, 

294 col_offset=col_offset, 

295 end_col_offset=end_col_offset, 

296 end_lineno=end_lineno, 

297 parent=parent, 

298 ) 

299 if call is None: 

300 self.filled_args = list(filled_args or []) 

301 self.filled_keywords = dict(filled_keywords or {}) 

302 else: 

303 self.filled_args = call.positional_arguments[1:] 

304 self.filled_keywords = call.keyword_arguments 

305 

306 wrapped_function = call.positional_arguments[0] 

307 inferred_wrapped_function = next(wrapped_function.infer()) 

308 if isinstance(inferred_wrapped_function, PartialFunction): 

309 self.filled_args = ( 

310 inferred_wrapped_function.filled_args + self.filled_args 

311 ) 

312 self.filled_keywords = { 

313 **inferred_wrapped_function.filled_keywords, 

314 **self.filled_keywords, 

315 } 

316 

317 self.filled_positionals = len(self.filled_args) 

318 

319 def infer_call_result( 

320 self, 

321 caller: SuccessfulInferenceResult | None, 

322 context: InferenceContext | None = None, 

323 ) -> Iterator[InferenceResult]: 

324 if context: 

325 assert ( 

326 context.callcontext 

327 ), "CallContext should be set before inferring call result" 

328 current_passed_keywords = { 

329 keyword for (keyword, _) in context.callcontext.keywords 

330 } 

331 for keyword, value in self.filled_keywords.items(): 

332 if keyword not in current_passed_keywords: 

333 context.callcontext.keywords.append((keyword, value)) 

334 

335 call_context_args = context.callcontext.args or [] 

336 context.callcontext.args = self.filled_args + call_context_args 

337 

338 return super().infer_call_result(caller=caller, context=context) 

339 

340 def qname(self) -> str: 

341 return self.__class__.__name__ 

342 

343 

344# TODO: Hack to solve the circular import problem between node_classes and objects 

345# This is not needed in 2.0, which has a cleaner design overall 

346node_classes.Dict.__bases__ = (node_classes.NodeNG, DictInstance) 

347 

348 

349class Property(scoped_nodes.FunctionDef): 

350 """Class representing a Python property.""" 

351 

352 def __init__(self, function, name=None, lineno=None, col_offset=None, parent=None): 

353 self.function = function 

354 super().__init__( 

355 name, 

356 lineno=lineno, 

357 col_offset=col_offset, 

358 parent=parent, 

359 end_col_offset=function.end_col_offset, 

360 end_lineno=function.end_lineno, 

361 ) 

362 

363 special_attributes = objectmodel.PropertyModel() 

364 type = "property" 

365 

366 def pytype(self) -> Literal["builtins.property"]: 

367 return "builtins.property" 

368 

369 def callable(self) -> Literal[False]: 

370 return False 

371 

372 def infer_call_result( 

373 self, 

374 caller: SuccessfulInferenceResult | None, 

375 context: InferenceContext | None = None, 

376 ) -> NoReturn: 

377 raise InferenceError("Properties are not callable") 

378 

379 def _infer(self, context: InferenceContext | None = None) -> Generator[Self]: 

380 yield self