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___name__(self):
782 return node_classes.Const(
783 value=self._instance.parent.name, parent=self._instance
784 )
785
786 @property
787 def attr___doc__(self):
788 return node_classes.Const(
789 value=getattr(self._instance.parent.doc_node, "value", None),
790 parent=self._instance,
791 )
792
793
794class GeneratorModel(GeneratorBaseModel):
795 def __init__(self):
796 super().__init__(AstroidManager().builtins_module["generator"])
797
798
799class AsyncGeneratorModel(GeneratorBaseModel):
800 def __init__(self):
801 super().__init__(AstroidManager().builtins_module["async_generator"])
802
803
804class InstanceModel(ObjectModel):
805 @property
806 def attr___class__(self):
807 return self._instance._proxied
808
809 @property
810 def attr___module__(self):
811 return node_classes.Const(self._instance.root().qname())
812
813 @property
814 def attr___doc__(self):
815 return node_classes.Const(getattr(self._instance.doc_node, "value", None))
816
817 @property
818 def attr___dict__(self):
819 return _dunder_dict(self._instance, self._instance.instance_attrs)
820
821
822# Exception instances
823
824
825class ExceptionInstanceModel(InstanceModel):
826 @property
827 def attr_args(self) -> bases.Instance:
828 # The arguments an exception was created with are not known from the
829 # instance alone, so ``args`` is a tuple of unknown contents rather
830 # than a known empty tuple.
831 builtins_ast_module = AstroidManager().builtins_module
832 return builtins_ast_module["tuple"].instantiate_class()
833
834 @property
835 def attr___traceback__(self):
836 builtins_ast_module = AstroidManager().builtins_module
837 traceback_type = builtins_ast_module[types.TracebackType.__name__]
838 return traceback_type.instantiate_class()
839
840
841class SyntaxErrorInstanceModel(ExceptionInstanceModel):
842 @property
843 def attr_text(self):
844 return node_classes.Const("")
845
846
847class GroupExceptionInstanceModel(ExceptionInstanceModel):
848 @property
849 def attr_exceptions(self) -> nodes.Tuple:
850 return node_classes.Tuple(parent=self._instance)
851
852
853class OSErrorInstanceModel(ExceptionInstanceModel):
854 @property
855 def attr_filename(self):
856 return node_classes.Const("")
857
858 @property
859 def attr_errno(self):
860 return node_classes.Const(0)
861
862 @property
863 def attr_strerror(self):
864 return node_classes.Const("")
865
866 attr_filename2 = attr_filename
867
868
869class ImportErrorInstanceModel(ExceptionInstanceModel):
870 @property
871 def attr_name(self):
872 return node_classes.Const("")
873
874 @property
875 def attr_path(self):
876 return node_classes.Const("")
877
878
879class UnicodeDecodeErrorInstanceModel(ExceptionInstanceModel):
880 @property
881 def attr_object(self):
882 return node_classes.Const(b"")
883
884
885BUILTIN_EXCEPTIONS = {
886 "builtins.SyntaxError": SyntaxErrorInstanceModel,
887 "builtins.ExceptionGroup": GroupExceptionInstanceModel,
888 "builtins.ImportError": ImportErrorInstanceModel,
889 "builtins.UnicodeDecodeError": UnicodeDecodeErrorInstanceModel,
890 # These are all similar to OSError in terms of attributes
891 "builtins.OSError": OSErrorInstanceModel,
892 "builtins.BlockingIOError": OSErrorInstanceModel,
893 "builtins.BrokenPipeError": OSErrorInstanceModel,
894 "builtins.ChildProcessError": OSErrorInstanceModel,
895 "builtins.ConnectionAbortedError": OSErrorInstanceModel,
896 "builtins.ConnectionError": OSErrorInstanceModel,
897 "builtins.ConnectionRefusedError": OSErrorInstanceModel,
898 "builtins.ConnectionResetError": OSErrorInstanceModel,
899 "builtins.FileExistsError": OSErrorInstanceModel,
900 "builtins.FileNotFoundError": OSErrorInstanceModel,
901 "builtins.InterruptedError": OSErrorInstanceModel,
902 "builtins.IsADirectoryError": OSErrorInstanceModel,
903 "builtins.NotADirectoryError": OSErrorInstanceModel,
904 "builtins.PermissionError": OSErrorInstanceModel,
905 "builtins.ProcessLookupError": OSErrorInstanceModel,
906 "builtins.TimeoutError": OSErrorInstanceModel,
907}
908
909
910class DictModel(ObjectModel):
911 @property
912 def attr___class__(self):
913 return self._instance._proxied
914
915 def _generic_dict_attribute(self, obj, name):
916 """Generate a bound method that can infer the given *obj*."""
917
918 class DictMethodBoundMethod(astroid.BoundMethod):
919 def infer_call_result(
920 self,
921 caller: SuccessfulInferenceResult | None,
922 context: InferenceContext | None = None,
923 ) -> Iterator[InferenceResult]:
924 yield obj
925
926 meth = next(self._instance._proxied.igetattr(name), None)
927 return DictMethodBoundMethod(proxy=meth, bound=self._instance)
928
929 @property
930 def attr_items(self):
931 from astroid import objects # pylint: disable=import-outside-toplevel
932
933 elems = []
934 obj = node_classes.List(parent=self._instance)
935 for key, value in self._instance.items:
936 elem = node_classes.Tuple(parent=obj)
937 elem.postinit((key, value))
938 elems.append(elem)
939 obj.postinit(elts=elems)
940
941 items_obj = objects.DictItems(obj)
942 return self._generic_dict_attribute(items_obj, "items")
943
944 @property
945 def attr_keys(self):
946 from astroid import objects # pylint: disable=import-outside-toplevel
947
948 keys = [key for (key, _) in self._instance.items]
949 obj = node_classes.List(parent=self._instance)
950 obj.postinit(elts=keys)
951
952 keys_obj = objects.DictKeys(obj)
953 return self._generic_dict_attribute(keys_obj, "keys")
954
955 @property
956 def attr_values(self):
957 from astroid import objects # pylint: disable=import-outside-toplevel
958
959 values = [value for (_, value) in self._instance.items]
960 obj = node_classes.List(parent=self._instance)
961 obj.postinit(values)
962
963 values_obj = objects.DictValues(obj)
964 return self._generic_dict_attribute(values_obj, "values")
965
966
967class PropertyModel(ObjectModel):
968 """Model for a builtin property."""
969
970 def _init_function(self, name):
971 function = nodes.FunctionDef(
972 name=name,
973 parent=self._instance,
974 lineno=self._instance.lineno,
975 col_offset=self._instance.col_offset,
976 end_lineno=self._instance.end_lineno,
977 end_col_offset=self._instance.end_col_offset,
978 )
979
980 args = nodes.Arguments(parent=function, vararg=None, kwarg=None)
981 args.postinit(
982 args=[],
983 defaults=[],
984 kwonlyargs=[],
985 kw_defaults=[],
986 annotations=[],
987 posonlyargs=[],
988 posonlyargs_annotations=[],
989 kwonlyargs_annotations=[],
990 )
991
992 function.postinit(args=args, body=[])
993 return function
994
995 @property
996 def attr_fget(self):
997 func = self._instance
998
999 class PropertyFuncAccessor(nodes.FunctionDef):
1000 def infer_call_result(
1001 self,
1002 caller: SuccessfulInferenceResult | None,
1003 context: InferenceContext | None = None,
1004 ) -> Iterator[InferenceResult]:
1005 nonlocal func
1006 if caller and len(caller.args) != 1:
1007 raise InferenceError(
1008 "fget() needs a single argument", target=self, context=context
1009 )
1010
1011 yield from func.function.infer_call_result(
1012 caller=caller, context=context
1013 )
1014
1015 property_accessor = PropertyFuncAccessor(
1016 name="fget",
1017 parent=self._instance,
1018 lineno=self._instance.lineno,
1019 col_offset=self._instance.col_offset,
1020 end_lineno=self._instance.end_lineno,
1021 end_col_offset=self._instance.end_col_offset,
1022 )
1023 property_accessor.postinit(args=func.args, body=func.body)
1024 return property_accessor
1025
1026 @property
1027 def attr_fset(self):
1028 func = self._instance
1029
1030 def find_setter(func: Property) -> nodes.FunctionDef | None:
1031 """
1032 Given a property, find the corresponding setter function and returns it.
1033
1034 :param func: property for which the setter has to be found
1035 :return: the setter function or None
1036 """
1037 for node in func.parent.body:
1038 if isinstance(node, (nodes.FunctionDef, nodes.AsyncFunctionDef)):
1039 for dec_name in node.decoratornames():
1040 if dec_name.endswith(func.function.name + ".setter"):
1041 return node
1042 return None
1043
1044 func_setter = find_setter(func)
1045 if not func_setter:
1046 raise InferenceError(
1047 f"Unable to find the setter of property {func.function.name}"
1048 )
1049
1050 class PropertyFuncAccessor(nodes.FunctionDef):
1051 def infer_call_result(
1052 self,
1053 caller: SuccessfulInferenceResult | None,
1054 context: InferenceContext | None = None,
1055 ) -> Iterator[InferenceResult]:
1056 nonlocal func_setter
1057 if caller and len(caller.args) != 2:
1058 raise InferenceError(
1059 "fset() needs two arguments", target=self, context=context
1060 )
1061 yield from func_setter.infer_call_result(caller=caller, context=context)
1062
1063 property_accessor = PropertyFuncAccessor(
1064 name="fset",
1065 parent=self._instance,
1066 lineno=self._instance.lineno,
1067 col_offset=self._instance.col_offset,
1068 end_lineno=self._instance.end_lineno,
1069 end_col_offset=self._instance.end_col_offset,
1070 )
1071 property_accessor.postinit(args=func_setter.args, body=func_setter.body)
1072 return property_accessor
1073
1074 @property
1075 def attr_setter(self):
1076 return self._init_function("setter")
1077
1078 @property
1079 def attr_deleter(self):
1080 return self._init_function("deleter")
1081
1082 @property
1083 def attr_getter(self):
1084 return self._init_function("getter")
1085
1086 # pylint: enable=import-outside-toplevel