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"""
6Data object model, as per https://docs.python.org/3/reference/datamodel.html.
7
8This module describes, at least partially, a data object model for some
9of astroid's nodes. The model contains special attributes that nodes such
10as functions, classes, modules etc have, such as __doc__, __class__,
11__module__ etc, being used when doing attribute lookups over nodes.
12
13For instance, inferring `obj.__class__` will first trigger an inference
14of the `obj` variable. If it was successfully inferred, then an attribute
15`__class__ will be looked for in the inferred object. This is the part
16where the data model occurs. The model is attached to those nodes
17and the lookup mechanism will try to see if attributes such as
18`__class__` are defined by the model or not. If they are defined,
19the model will be requested to return the corresponding value of that
20attribute. Thus the model can be viewed as a special part of the lookup
21mechanism.
22"""
23
24from __future__ import annotations
25
26import itertools
27import os
28import types
29from collections.abc import Iterator
30from functools import lru_cache
31from typing import TYPE_CHECKING, Any, Literal
32
33import astroid
34from astroid import bases, nodes, util
35from astroid.context import InferenceContext, copy_context
36from astroid.exceptions import AttributeInferenceError, InferenceError, NoDefault
37from astroid.manager import AstroidManager
38from astroid.nodes import node_classes
39from astroid.typing import InferenceResult, SuccessfulInferenceResult
40
41if TYPE_CHECKING:
42 from astroid.objects import Property
43
44IMPL_PREFIX = "attr_"
45LEN_OF_IMPL_PREFIX = len(IMPL_PREFIX)
46
47
48def _dunder_dict(instance, attributes):
49 obj = node_classes.Dict(
50 parent=instance,
51 lineno=instance.lineno,
52 col_offset=instance.col_offset,
53 end_lineno=instance.end_lineno,
54 end_col_offset=instance.end_col_offset,
55 )
56
57 # Convert the keys to node strings
58 keys = [
59 node_classes.Const(value=value, parent=obj) for value in list(attributes.keys())
60 ]
61
62 # The original attribute has a list of elements for each key,
63 # but that is not useful for retrieving the special attribute's value.
64 # In this case, we're picking the last value from each list.
65 values = [elem[-1] for elem in attributes.values()]
66
67 obj.postinit(list(zip(keys, values)))
68 return obj
69
70
71def _get_bound_node(model: ObjectModel) -> Any:
72 # TODO: Use isinstance instead of try ... except after _instance has typing
73 try:
74 return model._instance._proxied
75 except AttributeError:
76 return model._instance
77
78
79class ObjectModel:
80 def __init__(self):
81 self._instance = None
82
83 def __repr__(self):
84 import pprint # pylint: disable=import-outside-toplevel
85
86 result = []
87 cname = type(self).__name__
88 string = "%(cname)s(%(fields)s)"
89 alignment = len(cname) + 1
90 for field in sorted(self.attributes()):
91 width = max(80 - len(field) - alignment, 1)
92 try:
93 lines = pprint.pformat(field, indent=2, width=width).splitlines(True)
94 except ValueError:
95 lines = [f"<{type(field).__name__}>"]
96
97 inner = [lines[0]]
98 for line in lines[1:]:
99 inner.append(" " * alignment + line)
100 result.append(field)
101
102 return string % {
103 "cname": cname,
104 "fields": (",\n" + " " * alignment).join(result),
105 }
106
107 def __call__(self, instance):
108 self._instance = instance
109 return self
110
111 def __get__(self, instance, cls=None):
112 # ObjectModel needs to be a descriptor so that just doing
113 # `special_attributes = SomeObjectModel` should be enough in the body of a node.
114 # But at the same time, node.special_attributes should return an object
115 # which can be used for manipulating the special attributes. That's the reason
116 # we pass the instance through which it got accessed to ObjectModel.__call__,
117 # returning itself afterwards, so we can still have access to the
118 # underlying data model and to the instance for which it got accessed.
119 return self(instance)
120
121 def __contains__(self, name) -> bool:
122 return name in self.attributes()
123
124 @lru_cache # noqa
125 def attributes(self) -> list[str]:
126 """Get the attributes which are exported by this object model."""
127 return [o[LEN_OF_IMPL_PREFIX:] for o in dir(self) if o.startswith(IMPL_PREFIX)]
128
129 def lookup(self, name):
130 """Look up the given *name* in the current model.
131
132 It should return an AST or an interpreter object,
133 but if the name is not found, then an AttributeInferenceError will be raised.
134 """
135 if name in self.attributes():
136 return getattr(self, IMPL_PREFIX + name)
137 raise AttributeInferenceError(target=self._instance, attribute=name)
138
139 @property
140 def attr___new__(self) -> bases.BoundMethod:
141 """Calling cls.__new__(type) on an object returns an instance of 'type'."""
142 from astroid import builder # pylint: disable=import-outside-toplevel
143
144 # ``__new__`` is a static method: the class is passed explicitly and
145 # ``BoundMethod.implicit_parameters()`` is 0 for it, so the first
146 # parameter is the one filled by ``cls`` in ``self.__new__(cls)`` or
147 # ``super().__new__(cls)``. The *args and **kwargs are necessary not
148 # to trigger warnings about extra parameters for ``__new__`` methods
149 # we don't infer correctly (e.g. ``tp_new`` of C types), just like
150 # the ``__init__`` fallback below.
151 node: nodes.FunctionDef = builder.extract_node(
152 """def __new__(cls, *args, **kwargs): return cls()"""
153 )
154 # We set the parent as being the ClassDef of 'object' as that
155 # triggers correct inference as a call to __new__ in bases.py
156 node.parent = AstroidManager().builtins_module["object"]
157
158 return bases.BoundMethod(proxy=node, bound=_get_bound_node(self))
159
160 @property
161 def attr___init__(self) -> bases.BoundMethod:
162 """Calling cls.__init__() normally returns None."""
163 from astroid import builder # pylint: disable=import-outside-toplevel
164
165 # The *args and **kwargs are necessary not to trigger warnings about missing
166 # or extra parameters for '__init__' methods we don't infer correctly.
167 # This BoundMethod is the fallback value for those.
168 node: nodes.FunctionDef = builder.extract_node(
169 """def __init__(self, *args, **kwargs): return None"""
170 )
171 # We set the parent as being the ClassDef of 'object' as that
172 # is where this method originally comes from
173 node.parent = AstroidManager().builtins_module["object"]
174
175 return bases.BoundMethod(proxy=node, bound=_get_bound_node(self))
176
177 # Base object attributes that return Unknown as fallback placeholders.
178 @property
179 def attr___ne__(self):
180 return node_classes.Unknown(parent=self._instance)
181
182 attr___class__ = attr___ne__
183 attr___delattr__ = attr___ne__
184 attr___dir__ = attr___ne__
185 attr___doc__ = attr___ne__
186 attr___eq__ = attr___ne__
187 attr___format__ = attr___ne__
188 attr___ge__ = attr___ne__
189 attr___getattribute__ = attr___ne__
190 attr___getstate__ = attr___ne__
191 attr___gt__ = attr___ne__
192 attr___hash__ = attr___ne__
193 attr___init_subclass__ = attr___ne__
194 attr___le__ = attr___ne__
195 attr___lt__ = attr___ne__
196 attr___reduce__ = attr___ne__
197 attr___reduce_ex__ = attr___ne__
198 attr___repr__ = attr___ne__
199 attr___setattr__ = attr___ne__
200 attr___sizeof__ = attr___ne__
201 attr___str__ = attr___ne__
202 attr___subclasshook__ = attr___ne__
203
204
205class ModuleModel(ObjectModel):
206 def _builtins(self):
207 builtins_ast_module = AstroidManager().builtins_module
208 return builtins_ast_module.special_attributes.lookup("__dict__")
209
210 @property
211 def attr_builtins(self):
212 return self._builtins()
213
214 @property
215 def attr___path__(self):
216 if not self._instance.package:
217 raise AttributeInferenceError(target=self._instance, attribute="__path__")
218
219 path_objs = [
220 node_classes.Const(
221 value=(
222 path if not path.endswith("__init__.py") else os.path.dirname(path)
223 ),
224 parent=self._instance,
225 )
226 for path in self._instance.path
227 ]
228
229 container = node_classes.List(parent=self._instance)
230 container.postinit(path_objs)
231
232 return container
233
234 @property
235 def attr___name__(self):
236 return node_classes.Const(value=self._instance.name, parent=self._instance)
237
238 @property
239 def attr___doc__(self):
240 return node_classes.Const(
241 value=getattr(self._instance.doc_node, "value", None),
242 parent=self._instance,
243 )
244
245 @property
246 def attr___file__(self):
247 return node_classes.Const(value=self._instance.file, parent=self._instance)
248
249 @property
250 def attr___dict__(self):
251 return _dunder_dict(self._instance, self._instance.globals)
252
253 @property
254 def attr___package__(self):
255 if not self._instance.package:
256 value = ""
257 else:
258 value = self._instance.name
259
260 return node_classes.Const(value=value, parent=self._instance)
261
262 # These are related to the Python 3 implementation of the
263 # import system,
264 # https://docs.python.org/3/reference/import.html#import-related-module-attributes
265
266 @property
267 def attr___spec__(self):
268 # No handling for now.
269 return node_classes.Unknown(parent=self._instance)
270
271 @property
272 def attr___loader__(self):
273 # No handling for now.
274 return node_classes.Unknown(parent=self._instance)
275
276 @property
277 def attr___cached__(self):
278 # No handling for now.
279 return node_classes.Unknown(parent=self._instance)
280
281
282class FunctionModel(ObjectModel):
283 def _is_builtin_func(self) -> bool:
284 func = self._instance
285 return isinstance(func.parent, nodes.Module) and not func.root().pure_python
286
287 @property
288 def attr___name__(self):
289 return node_classes.Const(value=self._instance.name, parent=self._instance)
290
291 @property
292 def attr___doc__(self):
293 return node_classes.Const(
294 value=getattr(self._instance.doc_node, "value", None),
295 parent=self._instance,
296 )
297
298 @property
299 def attr___qualname__(self):
300 return node_classes.Const(value=self._instance.qname(), parent=self._instance)
301
302 @property
303 def attr___defaults__(self):
304 func = self._instance
305 if self._is_builtin_func():
306 raise AttributeInferenceError(target=func, attribute="__defaults__")
307 if not func.args.defaults:
308 return node_classes.Const(value=None, parent=func)
309
310 defaults_obj = node_classes.Tuple(parent=func)
311 defaults_obj.postinit(func.args.defaults)
312 return defaults_obj
313
314 @property
315 def attr___annotations__(self):
316 if self._is_builtin_func():
317 raise AttributeInferenceError(
318 target=self._instance, attribute="__annotations__"
319 )
320 obj = node_classes.Dict(
321 parent=self._instance,
322 lineno=self._instance.lineno,
323 col_offset=self._instance.col_offset,
324 end_lineno=self._instance.end_lineno,
325 end_col_offset=self._instance.end_col_offset,
326 )
327
328 if not self._instance.returns:
329 returns = None
330 else:
331 returns = self._instance.returns
332
333 args = self._instance.args
334 pair_annotations = itertools.chain(
335 zip(args.args or [], args.annotations),
336 zip(args.kwonlyargs, args.kwonlyargs_annotations),
337 zip(args.posonlyargs or [], args.posonlyargs_annotations),
338 )
339
340 annotations = {
341 arg.name: annotation for (arg, annotation) in pair_annotations if annotation
342 }
343 if args.varargannotation:
344 annotations[args.vararg] = args.varargannotation
345 if args.kwargannotation:
346 annotations[args.kwarg] = args.kwargannotation
347 if returns:
348 annotations["return"] = returns
349
350 items = [
351 (node_classes.Const(key, parent=obj), value)
352 for (key, value) in annotations.items()
353 ]
354
355 obj.postinit(items)
356 return obj
357
358 @property
359 def attr___dict__(self):
360 if self._is_builtin_func():
361 raise AttributeInferenceError(target=self._instance, attribute="__dict__")
362 return node_classes.Dict(
363 parent=self._instance,
364 lineno=self._instance.lineno,
365 col_offset=self._instance.col_offset,
366 end_lineno=self._instance.end_lineno,
367 end_col_offset=self._instance.end_col_offset,
368 )
369
370 @property
371 def attr___globals__(self):
372 if self._is_builtin_func():
373 raise AttributeInferenceError(
374 target=self._instance, attribute="__globals__"
375 )
376 return node_classes.Dict(
377 parent=self._instance,
378 lineno=self._instance.lineno,
379 col_offset=self._instance.col_offset,
380 end_lineno=self._instance.end_lineno,
381 end_col_offset=self._instance.end_col_offset,
382 )
383
384 @property
385 def attr___kwdefaults__(self):
386 if self._is_builtin_func():
387 raise AttributeInferenceError(
388 target=self._instance, attribute="__kwdefaults__"
389 )
390
391 def _default_args(args, parent):
392 for arg in args.kwonlyargs:
393 try:
394 default = args.default_value(arg.name)
395 except NoDefault:
396 continue
397
398 name = node_classes.Const(arg.name, parent=parent)
399 yield name, default
400
401 args = self._instance.args
402 obj = node_classes.Dict(
403 parent=self._instance,
404 lineno=self._instance.lineno,
405 col_offset=self._instance.col_offset,
406 end_lineno=self._instance.end_lineno,
407 end_col_offset=self._instance.end_col_offset,
408 )
409 defaults = dict(_default_args(args, obj))
410
411 obj.postinit(list(defaults.items()))
412 return obj
413
414 @property
415 def attr___module__(self):
416 return node_classes.Const(self._instance.root().qname())
417
418 @property
419 def attr___get__(self):
420 func = self._instance
421
422 if self._is_builtin_func():
423 raise AttributeInferenceError(target=func, attribute="__get__")
424
425 class DescriptorBoundMethod(bases.BoundMethod):
426 """Bound method which knows how to understand calling descriptor
427 binding.
428 """
429
430 def implicit_parameters(self) -> Literal[0]:
431 # Different than BoundMethod since the signature
432 # is different.
433 return 0
434
435 def infer_call_result(
436 self,
437 caller: SuccessfulInferenceResult | None,
438 context: InferenceContext | None = None,
439 ) -> Iterator[bases.BoundMethod]:
440 if len(caller.args) > 2 or len(caller.args) < 1:
441 raise InferenceError(
442 "Invalid arguments for descriptor binding",
443 target=self,
444 context=context,
445 )
446
447 context = copy_context(context)
448 try:
449 cls = next(caller.args[0].infer(context=context))
450 except StopIteration as e:
451 raise InferenceError(context=context, node=caller.args[0]) from e
452
453 if isinstance(cls, util.UninferableBase):
454 raise InferenceError(
455 "Invalid class inferred", target=self, context=context
456 )
457
458 # The `func` can already be a Unbound or BoundMethod. If the former, make sure to
459 # wrap as a BoundMethod like we do below when constructing the function from scratch.
460 if isinstance(func, bases.UnboundMethod):
461 yield bases.BoundMethod(proxy=func, bound=cls)
462 return
463
464 if isinstance(func, bases.BoundMethod):
465 yield func
466 return
467
468 # Rebuild the original value, but with the parent set as the
469 # class where it will be bound.
470 new_func_kwargs = {
471 "name": func.name,
472 "lineno": func.lineno,
473 "col_offset": func.col_offset,
474 "parent": func.parent,
475 "end_lineno": func.end_lineno,
476 "end_col_offset": func.end_col_offset,
477 }
478 if isinstance(func, astroid.objects.PartialFunction):
479 new_func_kwargs["filled_args"] = func.filled_args
480 new_func_kwargs["filled_keywords"] = func.filled_keywords
481
482 new_func = func.__class__(**new_func_kwargs)
483 # pylint: disable=no-member
484 new_func.postinit(
485 func.args,
486 func.body,
487 func.decorators,
488 func.returns,
489 doc_node=func.doc_node,
490 )
491
492 # Build a proper bound method that points to our newly built function.
493 proxy = bases.UnboundMethod(new_func)
494 yield bases.BoundMethod(proxy=proxy, bound=cls)
495
496 @property
497 def args(self):
498 """Overwrite the underlying args to match those of the underlying func.
499
500 Usually the underlying *func* is a function/method, as in:
501
502 def test(self):
503 pass
504
505 This has only the *self* parameter but when we access test.__get__
506 we get a new object which has two parameters, *self* and *type*.
507 """
508 nonlocal func
509 arguments = nodes.Arguments(
510 parent=func.args.parent, vararg=None, kwarg=None
511 )
512
513 positional_or_keyword_params = func.args.args.copy()
514 positional_or_keyword_params.append(
515 nodes.AssignName(
516 name="type",
517 lineno=0,
518 col_offset=0,
519 parent=arguments,
520 end_lineno=None,
521 end_col_offset=None,
522 )
523 )
524
525 positional_only_params = func.args.posonlyargs.copy()
526
527 arguments.postinit(
528 args=positional_or_keyword_params,
529 posonlyargs=positional_only_params,
530 defaults=[],
531 kwonlyargs=[],
532 kw_defaults=[],
533 annotations=[],
534 kwonlyargs_annotations=[],
535 posonlyargs_annotations=[],
536 )
537 return arguments
538
539 return DescriptorBoundMethod(proxy=self._instance, bound=self._instance)
540
541 # Function-specific attributes.
542 @property
543 def attr___call__(self):
544 return node_classes.Unknown(parent=self._instance)
545
546 attr___builtins__ = attr___call__
547 attr___closure__ = attr___call__
548 attr___code__ = attr___call__
549 attr___type_params__ = attr___call__
550
551
552class ClassModel(ObjectModel):
553 def __init__(self):
554 # Add a context so that inferences called from an instance don't recurse endlessly
555 self.context = InferenceContext()
556
557 super().__init__()
558
559 @property
560 def attr___annotations__(self) -> node_classes.Unknown:
561 return node_classes.Unknown(parent=self._instance)
562
563 @property
564 def attr___module__(self):
565 return node_classes.Const(self._instance.root().qname())
566
567 @property
568 def attr___name__(self):
569 return node_classes.Const(self._instance.name)
570
571 @property
572 def attr___qualname__(self):
573 return node_classes.Const(self._instance.qname())
574
575 @property
576 def attr___doc__(self):
577 return node_classes.Const(getattr(self._instance.doc_node, "value", None))
578
579 @property
580 def attr___mro__(self):
581 mro = self._instance.mro()
582 obj = node_classes.Tuple(parent=self._instance)
583 obj.postinit(mro)
584 return obj
585
586 @property
587 def attr_mro(self):
588 other_self = self
589
590 # Cls.mro is a method and we need to return one in order to have a proper inference.
591 # The method we're returning is capable of inferring the underlying MRO though.
592 class MroBoundMethod(bases.BoundMethod):
593 def infer_call_result(
594 self,
595 caller: SuccessfulInferenceResult | None,
596 context: InferenceContext | None = None,
597 ) -> Iterator[node_classes.Tuple]:
598 yield other_self.attr___mro__
599
600 implicit_metaclass = self._instance.implicit_metaclass()
601 mro_method = implicit_metaclass.locals["mro"][0]
602 return MroBoundMethod(proxy=mro_method, bound=implicit_metaclass)
603
604 @property
605 def attr___bases__(self):
606 obj = node_classes.Tuple(parent=self._instance)
607 context = InferenceContext()
608 elts = list(self._instance._inferred_bases(context))
609 obj.postinit(elts=elts)
610 return obj
611
612 @property
613 def attr___class__(self):
614 # pylint: disable=import-outside-toplevel; circular import
615 from astroid import helpers
616
617 return helpers.object_type(self._instance)
618
619 @property
620 def attr___subclasses__(self):
621 """Get the subclasses of the underlying class.
622
623 This looks only in the current module for retrieving the subclasses,
624 thus it might miss a couple of them.
625 """
626
627 qname = self._instance.qname()
628 root = self._instance.root()
629 classes = [
630 cls
631 for cls in root.nodes_of_class(nodes.ClassDef)
632 if cls != self._instance and cls.is_subtype_of(qname, context=self.context)
633 ]
634
635 obj = node_classes.List(parent=self._instance)
636 obj.postinit(classes)
637
638 class SubclassesBoundMethod(bases.BoundMethod):
639 def infer_call_result(
640 self,
641 caller: SuccessfulInferenceResult | None,
642 context: InferenceContext | None = None,
643 ) -> Iterator[node_classes.List]:
644 yield obj
645
646 implicit_metaclass = self._instance.implicit_metaclass()
647 subclasses_method = implicit_metaclass.locals["__subclasses__"][0]
648 return SubclassesBoundMethod(proxy=subclasses_method, bound=implicit_metaclass)
649
650 @property
651 def attr___dict__(self):
652 return node_classes.Dict(
653 parent=self._instance,
654 lineno=self._instance.lineno,
655 col_offset=self._instance.col_offset,
656 end_lineno=self._instance.end_lineno,
657 end_col_offset=self._instance.end_col_offset,
658 )
659
660 @property
661 def attr___call__(self):
662 """Calling a class A() returns an instance of A."""
663 return self._instance.instantiate_class()
664
665
666class SuperModel(ObjectModel):
667 @property
668 def attr___thisclass__(self):
669 return self._instance.mro_pointer
670
671 @property
672 def attr___self_class__(self):
673 return self._instance._self_class
674
675 @property
676 def attr___self__(self):
677 return self._instance.type
678
679 @property
680 def attr___class__(self):
681 return self._instance._proxied
682
683
684class UnboundMethodModel(FunctionModel):
685 @property
686 def attr___class__(self):
687 # pylint: disable=import-outside-toplevel; circular import
688 from astroid import helpers
689
690 return helpers.object_type(self._instance)
691
692 @property
693 def attr___func__(self):
694 return self._instance._proxied
695
696 @property
697 def attr___self__(self):
698 return node_classes.Const(value=None, parent=self._instance)
699
700 attr_im_func = attr___func__
701 attr_im_class = attr___class__
702 attr_im_self = attr___self__
703
704
705class ContextManagerModel(ObjectModel):
706 """Model for context managers.
707
708 Based on 3.3.9 of the Data Model documentation:
709 https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers
710 """
711
712 @property
713 def attr___enter__(self) -> bases.BoundMethod:
714 """Representation of the base implementation of __enter__.
715
716 As per Python documentation:
717 Enter the runtime context related to this object. The with statement
718 will bind this method's return value to the target(s) specified in the
719 as clause of the statement, if any.
720 """
721 from astroid import builder # pylint: disable=import-outside-toplevel
722
723 node: nodes.FunctionDef = builder.extract_node("""def __enter__(self): ...""")
724 # We set the parent as being the ClassDef of 'object' as that
725 # is where this method originally comes from
726 node.parent = AstroidManager().builtins_module["object"]
727
728 return bases.BoundMethod(proxy=node, bound=_get_bound_node(self))
729
730 @property
731 def attr___exit__(self) -> bases.BoundMethod:
732 """Representation of the base implementation of __exit__.
733
734 As per Python documentation:
735 Exit the runtime context related to this object. The parameters describe the
736 exception that caused the context to be exited. If the context was exited
737 without an exception, all three arguments will be None.
738 """
739 from astroid import builder # pylint: disable=import-outside-toplevel
740
741 node: nodes.FunctionDef = builder.extract_node(
742 """def __exit__(self, exc_type, exc_value, traceback): ..."""
743 )
744 # We set the parent as being the ClassDef of 'object' as that
745 # is where this method originally comes from
746 node.parent = AstroidManager().builtins_module["object"]
747
748 return bases.BoundMethod(proxy=node, bound=_get_bound_node(self))
749
750
751class BoundMethodModel(FunctionModel):
752 @property
753 def attr___func__(self):
754 # Proxy depth varies: an instance method accessed through an instance
755 # proxies another method proxy, a classmethod on its class or a lambda
756 # class attribute proxies the function directly.
757 proxied = self._instance._proxied
758 while isinstance(proxied, bases.UnboundMethod):
759 proxied = proxied._proxied
760 return proxied
761
762 @property
763 def attr___self__(self):
764 return self._instance.bound
765
766
767class GeneratorBaseModel(FunctionModel, ContextManagerModel):
768 def __init__(self, gen_module: nodes.Module):
769 super().__init__()
770 for name, values in gen_module.locals.items():
771 method = values[0]
772 if isinstance(method, nodes.FunctionDef):
773 method = bases.BoundMethod(method, _get_bound_node(self))
774
775 def patched(cls, meth=method):
776 return meth
777
778 setattr(type(self), IMPL_PREFIX + name, property(patched))
779
780 @property
781 def attr___get__(self):
782 # Generators are not descriptors
783 raise AttributeInferenceError(target=self._instance, attribute="__get__")
784
785 @property
786 def attr___name__(self):
787 return node_classes.Const(
788 value=self._instance.parent.name, parent=self._instance
789 )
790
791 @property
792 def attr___doc__(self):
793 return node_classes.Const(
794 value=getattr(self._instance.parent.doc_node, "value", None),
795 parent=self._instance,
796 )
797
798
799class GeneratorModel(GeneratorBaseModel):
800 def __init__(self):
801 super().__init__(AstroidManager().builtins_module["generator"])
802
803
804class AsyncGeneratorModel(GeneratorBaseModel):
805 def __init__(self):
806 super().__init__(AstroidManager().builtins_module["async_generator"])
807
808
809class InstanceModel(ObjectModel):
810 @property
811 def attr___class__(self):
812 return self._instance._proxied
813
814 @property
815 def attr___module__(self):
816 return node_classes.Const(self._instance.root().qname())
817
818 @property
819 def attr___doc__(self):
820 return node_classes.Const(getattr(self._instance.doc_node, "value", None))
821
822 @property
823 def attr___dict__(self):
824 return _dunder_dict(self._instance, self._instance.instance_attrs)
825
826
827# Exception instances
828
829
830class ExceptionInstanceModel(InstanceModel):
831 @property
832 def attr_args(self) -> bases.Instance:
833 # The arguments an exception was created with are not known from the
834 # instance alone, so ``args`` is a tuple of unknown contents rather
835 # than a known empty tuple.
836 builtins_ast_module = AstroidManager().builtins_module
837 return builtins_ast_module["tuple"].instantiate_class()
838
839 @property
840 def attr___traceback__(self):
841 builtins_ast_module = AstroidManager().builtins_module
842 traceback_type = builtins_ast_module[types.TracebackType.__name__]
843 return traceback_type.instantiate_class()
844
845
846class SyntaxErrorInstanceModel(ExceptionInstanceModel):
847 @property
848 def attr_text(self):
849 return node_classes.Const("")
850
851
852class GroupExceptionInstanceModel(ExceptionInstanceModel):
853 @property
854 def attr_exceptions(self) -> nodes.Tuple:
855 return node_classes.Tuple(parent=self._instance)
856
857
858class OSErrorInstanceModel(ExceptionInstanceModel):
859 @property
860 def attr_filename(self):
861 return node_classes.Const("")
862
863 @property
864 def attr_errno(self):
865 return node_classes.Const(0)
866
867 @property
868 def attr_strerror(self):
869 return node_classes.Const("")
870
871 attr_filename2 = attr_filename
872
873
874class ImportErrorInstanceModel(ExceptionInstanceModel):
875 @property
876 def attr_name(self):
877 return node_classes.Const("")
878
879 @property
880 def attr_path(self):
881 return node_classes.Const("")
882
883
884class UnicodeDecodeErrorInstanceModel(ExceptionInstanceModel):
885 @property
886 def attr_object(self):
887 return node_classes.Const(b"")
888
889
890BUILTIN_EXCEPTIONS = {
891 "builtins.SyntaxError": SyntaxErrorInstanceModel,
892 "builtins.ExceptionGroup": GroupExceptionInstanceModel,
893 "builtins.ImportError": ImportErrorInstanceModel,
894 "builtins.UnicodeDecodeError": UnicodeDecodeErrorInstanceModel,
895 # These are all similar to OSError in terms of attributes
896 "builtins.OSError": OSErrorInstanceModel,
897 "builtins.BlockingIOError": OSErrorInstanceModel,
898 "builtins.BrokenPipeError": OSErrorInstanceModel,
899 "builtins.ChildProcessError": OSErrorInstanceModel,
900 "builtins.ConnectionAbortedError": OSErrorInstanceModel,
901 "builtins.ConnectionError": OSErrorInstanceModel,
902 "builtins.ConnectionRefusedError": OSErrorInstanceModel,
903 "builtins.ConnectionResetError": OSErrorInstanceModel,
904 "builtins.FileExistsError": OSErrorInstanceModel,
905 "builtins.FileNotFoundError": OSErrorInstanceModel,
906 "builtins.InterruptedError": OSErrorInstanceModel,
907 "builtins.IsADirectoryError": OSErrorInstanceModel,
908 "builtins.NotADirectoryError": OSErrorInstanceModel,
909 "builtins.PermissionError": OSErrorInstanceModel,
910 "builtins.ProcessLookupError": OSErrorInstanceModel,
911 "builtins.TimeoutError": OSErrorInstanceModel,
912}
913
914
915class DictModel(ObjectModel):
916 @property
917 def attr___class__(self):
918 return self._instance._proxied
919
920 def _generic_dict_attribute(self, obj, name):
921 """Generate a bound method that can infer the given *obj*."""
922
923 class DictMethodBoundMethod(astroid.BoundMethod):
924 def infer_call_result(
925 self,
926 caller: SuccessfulInferenceResult | None,
927 context: InferenceContext | None = None,
928 ) -> Iterator[InferenceResult]:
929 yield obj
930
931 meth = next(self._instance._proxied.igetattr(name), None)
932 return DictMethodBoundMethod(proxy=meth, bound=self._instance)
933
934 @property
935 def attr_items(self):
936 from astroid import objects # pylint: disable=import-outside-toplevel
937
938 elems = []
939 obj = node_classes.List(parent=self._instance)
940 for key, value in self._instance.items:
941 elem = node_classes.Tuple(parent=obj)
942 elem.postinit((key, value))
943 elems.append(elem)
944 obj.postinit(elts=elems)
945
946 items_obj = objects.DictItems(obj)
947 return self._generic_dict_attribute(items_obj, "items")
948
949 @property
950 def attr_keys(self):
951 from astroid import objects # pylint: disable=import-outside-toplevel
952
953 keys = [key for (key, _) in self._instance.items]
954 obj = node_classes.List(parent=self._instance)
955 obj.postinit(elts=keys)
956
957 keys_obj = objects.DictKeys(obj)
958 return self._generic_dict_attribute(keys_obj, "keys")
959
960 @property
961 def attr_values(self):
962 from astroid import objects # pylint: disable=import-outside-toplevel
963
964 values = [value for (_, value) in self._instance.items]
965 obj = node_classes.List(parent=self._instance)
966 obj.postinit(values)
967
968 values_obj = objects.DictValues(obj)
969 return self._generic_dict_attribute(values_obj, "values")
970
971
972class PropertyModel(ObjectModel):
973 """Model for a builtin property."""
974
975 def _init_function(self, name):
976 function = nodes.FunctionDef(
977 name=name,
978 parent=self._instance,
979 lineno=self._instance.lineno,
980 col_offset=self._instance.col_offset,
981 end_lineno=self._instance.end_lineno,
982 end_col_offset=self._instance.end_col_offset,
983 )
984
985 args = nodes.Arguments(parent=function, vararg=None, kwarg=None)
986 args.postinit(
987 args=[],
988 defaults=[],
989 kwonlyargs=[],
990 kw_defaults=[],
991 annotations=[],
992 posonlyargs=[],
993 posonlyargs_annotations=[],
994 kwonlyargs_annotations=[],
995 )
996
997 function.postinit(args=args, body=[])
998 return function
999
1000 @property
1001 def attr_fget(self):
1002 func = self._instance
1003
1004 class PropertyFuncAccessor(nodes.FunctionDef):
1005 def infer_call_result(
1006 self,
1007 caller: SuccessfulInferenceResult | None,
1008 context: InferenceContext | None = None,
1009 ) -> Iterator[InferenceResult]:
1010 nonlocal func
1011 if caller and len(caller.args) != 1:
1012 raise InferenceError(
1013 "fget() needs a single argument", target=self, context=context
1014 )
1015
1016 yield from func.function.infer_call_result(
1017 caller=caller, context=context
1018 )
1019
1020 property_accessor = PropertyFuncAccessor(
1021 name="fget",
1022 parent=self._instance,
1023 lineno=self._instance.lineno,
1024 col_offset=self._instance.col_offset,
1025 end_lineno=self._instance.end_lineno,
1026 end_col_offset=self._instance.end_col_offset,
1027 )
1028 property_accessor.postinit(args=func.args, body=func.body)
1029 return property_accessor
1030
1031 @property
1032 def attr_fset(self):
1033 func = self._instance
1034
1035 def find_setter(func: Property) -> nodes.FunctionDef | None:
1036 """
1037 Given a property, find the corresponding setter function and returns it.
1038
1039 :param func: property for which the setter has to be found
1040 :return: the setter function or None
1041 """
1042 for node in func.parent.body:
1043 if isinstance(node, (nodes.FunctionDef, nodes.AsyncFunctionDef)):
1044 for dec_name in node.decoratornames():
1045 if dec_name.endswith(func.function.name + ".setter"):
1046 return node
1047 return None
1048
1049 func_setter = find_setter(func)
1050 if not func_setter:
1051 raise InferenceError(
1052 f"Unable to find the setter of property {func.function.name}"
1053 )
1054
1055 class PropertyFuncAccessor(nodes.FunctionDef):
1056 def infer_call_result(
1057 self,
1058 caller: SuccessfulInferenceResult | None,
1059 context: InferenceContext | None = None,
1060 ) -> Iterator[InferenceResult]:
1061 nonlocal func_setter
1062 if caller and len(caller.args) != 2:
1063 raise InferenceError(
1064 "fset() needs two arguments", target=self, context=context
1065 )
1066 yield from func_setter.infer_call_result(caller=caller, context=context)
1067
1068 property_accessor = PropertyFuncAccessor(
1069 name="fset",
1070 parent=self._instance,
1071 lineno=self._instance.lineno,
1072 col_offset=self._instance.col_offset,
1073 end_lineno=self._instance.end_lineno,
1074 end_col_offset=self._instance.end_col_offset,
1075 )
1076 property_accessor.postinit(args=func_setter.args, body=func_setter.body)
1077 return property_accessor
1078
1079 @property
1080 def attr_setter(self):
1081 return self._init_function("setter")
1082
1083 @property
1084 def attr_deleter(self):
1085 return self._init_function("deleter")
1086
1087 @property
1088 def attr_getter(self):
1089 return self._init_function("getter")
1090
1091 # pylint: enable=import-outside-toplevel