Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/raw_building.py: 71%
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
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
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
5"""this module contains a set of functions to create astroid trees from scratch
6(build_* functions) or from living object (object_build_* functions)
7"""
9from __future__ import annotations
11import builtins
12import inspect
13import io
14import os
15import sys
16import types
17import warnings
18from collections.abc import Iterable
19from contextlib import redirect_stderr, redirect_stdout
20from typing import TYPE_CHECKING, Any
22from astroid import bases, nodes
23from astroid.const import _EMPTY_OBJECT_MARKER, IS_PYPY
24from astroid.nodes import node_classes
26if TYPE_CHECKING:
27 from astroid.manager import AstroidManager
30_FunctionTypes = (
31 types.FunctionType
32 | types.MethodType
33 | types.BuiltinFunctionType
34 | types.WrapperDescriptorType
35 | types.MethodDescriptorType
36 | types.ClassMethodDescriptorType
37)
39TYPE_NONE = type(None)
40TYPE_NOTIMPLEMENTED = type(NotImplemented)
41TYPE_ELLIPSIS = type(...)
44def _attach_local_node(parent, node, name: str) -> None:
45 node.name = name # needed by add_local_node
46 parent.add_local_node(node)
49def _add_dunder_class(func, parent: nodes.NodeNG, member) -> None:
50 """Add a __class__ member to the given func node, if we can determine it."""
51 python_cls = member.__class__
52 cls_name = getattr(python_cls, "__name__", None)
53 if not cls_name:
54 return
55 cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__]
56 doc = python_cls.__doc__ if isinstance(python_cls.__doc__, str) else None
57 ast_klass = build_class(cls_name, parent, cls_bases, doc)
58 func.instance_attrs["__class__"] = [ast_klass]
61def build_dummy(runtime_object) -> nodes.EmptyNode:
62 enode = nodes.EmptyNode()
63 enode.object = runtime_object
64 return enode
67def attach_dummy_node(node, name: str, runtime_object=_EMPTY_OBJECT_MARKER) -> None:
68 """create a dummy node and register it in the locals of the given
69 node with the specified name
70 """
71 _attach_local_node(node, build_dummy(runtime_object), name)
74def attach_const_node(node, name: str, value) -> None:
75 """create a Const node and register it in the locals of the given
76 node with the specified name
77 """
78 # Special case: __hash__ = None overrides ObjectModel for unhashable types.
79 # See https://docs.python.org/3/reference/datamodel.html#object.__hash__
80 if name == "__hash__" and value is None:
81 _attach_local_node(node, nodes.const_factory(value), name)
82 elif name not in node.special_attributes:
83 _attach_local_node(node, nodes.const_factory(value), name)
86def attach_import_node(node, modname: str, membername: str) -> None:
87 """create a ImportFrom node and register it in the locals of the given
88 node with the specified name
89 """
90 from_node = nodes.ImportFrom(modname, [(membername, None)])
91 _attach_local_node(node, from_node, membername)
94def build_module(name: str, doc: str | None = None) -> nodes.Module:
95 """create and initialize an astroid Module node"""
96 node = nodes.Module(name, pure_python=False, package=False)
97 node.postinit(
98 body=[],
99 doc_node=nodes.Const(value=doc) if doc else None,
100 )
101 return node
104def build_class(
105 name: str,
106 parent: nodes.NodeNG,
107 basenames: Iterable[str] = (),
108 doc: str | None = None,
109) -> nodes.ClassDef:
110 """Create and initialize an astroid ClassDef node."""
111 node = nodes.ClassDef(
112 name,
113 lineno=0,
114 col_offset=0,
115 end_lineno=0,
116 end_col_offset=0,
117 parent=parent,
118 )
119 node.postinit(
120 bases=[
121 nodes.Name(
122 name=base,
123 lineno=0,
124 col_offset=0,
125 parent=node,
126 end_lineno=None,
127 end_col_offset=None,
128 )
129 for base in basenames
130 ],
131 body=[],
132 decorators=None,
133 doc_node=nodes.Const(value=doc) if doc else None,
134 )
135 return node
138def build_function(
139 name: str,
140 parent: nodes.NodeNG,
141 args: list[str] | None = None,
142 posonlyargs: list[str] | None = None,
143 defaults: list[Any] | None = None,
144 doc: str | None = None,
145 kwonlyargs: list[str] | None = None,
146 kwonlydefaults: list[Any] | None = None,
147) -> nodes.FunctionDef:
148 """create and initialize an astroid FunctionDef node"""
149 # first argument is now a list of decorators
150 func = nodes.FunctionDef(
151 name,
152 lineno=0,
153 col_offset=0,
154 parent=parent,
155 end_col_offset=0,
156 end_lineno=0,
157 )
158 argsnode = nodes.Arguments(parent=func, vararg=None, kwarg=None)
160 # If args is None we don't have any information about the signature
161 # (in contrast to when there are no arguments and args == []). We pass
162 # this to the builder to indicate this.
163 if args is not None:
164 # We set the lineno and col_offset to 0 because we don't have any
165 # information about the location of the function definition.
166 arguments = [
167 nodes.AssignName(
168 name=arg,
169 parent=argsnode,
170 lineno=0,
171 col_offset=0,
172 end_lineno=None,
173 end_col_offset=None,
174 )
175 for arg in args
176 ]
177 else:
178 arguments = None
180 default_nodes: list[nodes.NodeNG] | None
181 if defaults is None:
182 default_nodes = None
183 else:
184 default_nodes = []
185 for default in defaults:
186 default_node = nodes.const_factory(default)
187 default_node.parent = argsnode
188 default_nodes.append(default_node)
190 kwonlydefault_nodes: list[nodes.NodeNG | None] | None
191 if kwonlydefaults is None:
192 kwonlydefault_nodes = None
193 else:
194 kwonlydefault_nodes = []
195 for kwonlydefault in kwonlydefaults:
196 kwonlydefault_node = nodes.const_factory(kwonlydefault)
197 kwonlydefault_node.parent = argsnode
198 kwonlydefault_nodes.append(kwonlydefault_node)
200 # We set the lineno and col_offset to 0 because we don't have any
201 # information about the location of the kwonly and posonlyargs.
202 argsnode.postinit(
203 args=arguments,
204 defaults=default_nodes,
205 kwonlyargs=[
206 nodes.AssignName(
207 name=arg,
208 parent=argsnode,
209 lineno=0,
210 col_offset=0,
211 end_lineno=None,
212 end_col_offset=None,
213 )
214 for arg in kwonlyargs or ()
215 ],
216 kw_defaults=kwonlydefault_nodes,
217 annotations=[],
218 posonlyargs=[
219 nodes.AssignName(
220 name=arg,
221 parent=argsnode,
222 lineno=0,
223 col_offset=0,
224 end_lineno=None,
225 end_col_offset=None,
226 )
227 for arg in posonlyargs or ()
228 ],
229 kwonlyargs_annotations=[],
230 posonlyargs_annotations=[],
231 )
232 func.postinit(
233 args=argsnode,
234 body=[],
235 doc_node=nodes.Const(value=doc) if doc else None,
236 )
237 if args:
238 register_arguments(func)
239 return func
242def build_from_import(fromname: str, names: list[str]) -> nodes.ImportFrom:
243 """create and initialize an astroid ImportFrom import statement"""
244 return nodes.ImportFrom(fromname, [(name, None) for name in names])
247def register_arguments(func: nodes.FunctionDef, args: list | None = None) -> None:
248 """add given arguments to local
250 args is a list that may contains nested lists
251 (i.e. def func(a, (b, c, d)): ...)
252 """
253 # If no args are passed in, get the args from the function.
254 if args is None:
255 if func.args.vararg:
256 func.set_local(func.args.vararg, func.args)
257 if func.args.kwarg:
258 func.set_local(func.args.kwarg, func.args)
259 args = func.args.args
260 # If the function has no args, there is nothing left to do.
261 if args is None:
262 return
263 for arg in args:
264 if isinstance(arg, nodes.AssignName):
265 func.set_local(arg.name, arg)
266 else:
267 register_arguments(func, arg.elts)
270def _would_create_parent_cycle(node: nodes.NodeNG, child: nodes.NodeNG) -> bool:
271 """Whether making ``node`` the parent of ``child`` would close a parent loop.
273 That happens when ``child`` already is ``node`` or one of its ancestors.
274 """
275 ancestor: nodes.NodeNG | None = node
276 while ancestor is not None:
277 if ancestor is child:
278 return True
279 ancestor = ancestor.parent
280 return False
283def object_build_class(
284 node: nodes.Module | nodes.ClassDef, member: type
285) -> nodes.ClassDef:
286 """create astroid for a living class object"""
287 basenames = [base.__name__ for base in member.__bases__]
288 return _base_class_object_build(node, member, basenames)
291def _get_args_info_from_callable(
292 member: _FunctionTypes,
293) -> tuple[list[str], list[str], list[Any], list[str], list[Any]]:
294 """Returns args, posonlyargs, defaults, kwonlyargs.
296 :note: currently ignores the return annotation.
297 """
298 signature = inspect.signature(member)
299 args: list[str] = []
300 defaults: list[Any] = []
301 posonlyargs: list[str] = []
302 kwonlyargs: list[str] = []
303 kwonlydefaults: list[Any] = []
305 for param_name, param in signature.parameters.items():
306 if param.kind == inspect.Parameter.POSITIONAL_ONLY:
307 posonlyargs.append(param_name)
308 elif param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
309 args.append(param_name)
310 elif param.kind == inspect.Parameter.VAR_POSITIONAL:
311 args.append(param_name)
312 elif param.kind == inspect.Parameter.VAR_KEYWORD:
313 args.append(param_name)
314 elif param.kind == inspect.Parameter.KEYWORD_ONLY:
315 kwonlyargs.append(param_name)
316 if param.default is not inspect.Parameter.empty:
317 kwonlydefaults.append(param.default)
318 continue
319 if param.default is not inspect.Parameter.empty:
320 defaults.append(param.default)
322 return args, posonlyargs, defaults, kwonlyargs, kwonlydefaults
325def object_build_function(
326 node: nodes.Module | nodes.ClassDef, member: _FunctionTypes
327) -> nodes.FunctionDef:
328 """create astroid for a living function object"""
329 (
330 args,
331 posonlyargs,
332 defaults,
333 kwonlyargs,
334 kwonly_defaults,
335 ) = _get_args_info_from_callable(member)
337 return build_function(
338 getattr(member, "__name__", "<no-name>"),
339 node,
340 args,
341 posonlyargs,
342 defaults,
343 member.__doc__ if isinstance(member.__doc__, str) else None,
344 kwonlyargs=kwonlyargs,
345 kwonlydefaults=kwonly_defaults,
346 )
349def object_build_datadescriptor(
350 node: nodes.Module | nodes.ClassDef, member: type
351) -> nodes.EmptyNode:
352 """create astroid for a living data descriptor object
354 What the descriptor returns is not statically known, so it is modelled as an
355 unknown value. Modelling it as a class named after the attribute made
356 attribute access on the descriptor's value infer that class instead, which
357 reported the value's own attributes as missing.
358 """
359 return build_dummy(_EMPTY_OBJECT_MARKER)
362def object_build_methoddescriptor(
363 node: nodes.Module | nodes.ClassDef,
364 member: _FunctionTypes,
365) -> nodes.FunctionDef:
366 """create astroid for a living method descriptor object"""
367 # FIXME get arguments ?
368 name = getattr(member, "__name__", "<no-name>")
369 func = build_function(name, node, doc=member.__doc__)
370 _add_dunder_class(func, node, member)
371 return func
374def _base_class_object_build(
375 node: nodes.Module | nodes.ClassDef,
376 member: type,
377 basenames: list[str],
378) -> nodes.ClassDef:
379 """create astroid for a living class object, with a given set of base names
380 (e.g. ancestors)
381 """
382 name = getattr(member, "__name__", "<no-name>")
383 doc = member.__doc__ if isinstance(member.__doc__, str) else None
384 klass = build_class(name, node, basenames, doc)
385 try:
386 # limit the instantiation trick since it's too dangerous
387 # (such as infinite test execution...)
388 # this at least resolves common case such as Exception.args,
389 # OSError.errno
390 if issubclass(member, Exception):
391 member_object = member()
392 if hasattr(member_object, "__dict__"):
393 instdict = member_object.__dict__
394 else:
395 raise TypeError
396 else:
397 raise TypeError
398 except TypeError:
399 pass
400 else:
401 for item_name, obj in instdict.items():
402 valnode = nodes.EmptyNode()
403 valnode.object = obj
404 valnode.parent = klass
405 valnode.lineno = 1
406 klass.instance_attrs[item_name] = [valnode]
407 return klass
410def _build_from_function(
411 node: nodes.Module | nodes.ClassDef,
412 member: _FunctionTypes,
413 module: types.ModuleType,
414) -> nodes.FunctionDef | nodes.EmptyNode:
415 # verify this is not an imported function
416 try:
417 code = member.__code__ # type: ignore[union-attr]
418 except AttributeError:
419 # Some implementations don't provide the code object
420 code = None
421 filename = getattr(code, "co_filename", None)
422 if filename is None:
423 return object_build_methoddescriptor(node, member)
424 if filename == getattr(module, "__file__", None):
425 return object_build_function(node, member)
426 return build_dummy(member)
429def _safe_has_attribute(obj, member: str) -> bool:
430 """Required because unexpected RunTimeError can be raised.
432 See https://github.com/pylint-dev/astroid/issues/1958
433 """
434 try:
435 return hasattr(obj, member)
436 except Exception: # pylint: disable=broad-except
437 return False
440class InspectBuilder:
441 """class for building nodes from living object
443 this is actually a really minimal representation, including only Module,
444 FunctionDef and ClassDef nodes and some others as guessed.
445 """
447 bootstrapped: bool = False
449 def __init__(self, manager_instance: AstroidManager) -> None:
450 self._manager = manager_instance
451 self._done: dict[types.ModuleType | type, nodes.Module | nodes.ClassDef] = {}
452 self._module: types.ModuleType
454 def inspect_build(
455 self,
456 module: types.ModuleType,
457 modname: str | None = None,
458 path: str | None = None,
459 ) -> nodes.Module:
460 """build astroid from a living module (i.e. using inspect)
461 this is used when there is no python source code available (either
462 because it's a built-in module or because the .py is not available)
463 """
464 self._module = module
465 if modname is None:
466 modname = module.__name__
467 try:
468 node = build_module(modname, module.__doc__)
469 except AttributeError:
470 # in jython, java modules have no __doc__ (see #109562)
471 node = build_module(modname)
472 if path is None:
473 node.path = node.file = path
474 else:
475 node.path = [os.path.abspath(path)]
476 node.file = node.path[0]
477 node.name = modname
478 self._manager.cache_module(node)
479 node.package = hasattr(module, "__path__")
480 self._done = {}
481 self.object_build(node, module)
482 return node
484 def object_build(
485 self, node: nodes.Module | nodes.ClassDef, obj: types.ModuleType | type
486 ) -> None:
487 """recursive method which create a partial ast from real objects
488 (only function, class, and method are handled)
489 """
490 if obj in self._done:
491 return None
492 self._done[obj] = node
493 for alias in dir(obj):
494 # inspect.ismethod() and inspect.isbuiltin() in PyPy return
495 # the opposite of what they do in CPython for __class_getitem__.
496 pypy__class_getitem__ = IS_PYPY and alias == "__class_getitem__"
497 try:
498 with warnings.catch_warnings():
499 warnings.simplefilter("ignore")
500 member = getattr(obj, alias)
501 except (AttributeError, TypeError):
502 # AttributeError: damned ExtensionClass.Base, I know you're
503 # there!
504 # TypeError: PyPy 7.3.22 raises TypeError ("expected str, got
505 # getset_descriptor object") instead of AttributeError for
506 # unset getset descriptors like
507 # ``types.FunctionType.__text_signature__`` when accessed on
508 # the type. Treat that the same as a missing attribute so
509 # ``_astroid_bootstrapping()`` doesn't crash on import.
510 attach_dummy_node(node, alias)
511 continue
512 if inspect.ismethod(member) and not pypy__class_getitem__:
513 member = member.__func__
514 if inspect.isfunction(member):
515 child = _build_from_function(node, member, self._module)
516 elif inspect.isbuiltin(member) or pypy__class_getitem__:
517 if self.imported_member(node, member, alias):
518 continue
519 child = object_build_methoddescriptor(node, member)
520 elif inspect.isclass(member):
521 if self.imported_member(node, member, alias):
522 continue
523 if member in self._done:
524 child = self._done[member]
525 assert isinstance(child, nodes.ClassDef)
526 else:
527 child = object_build_class(node, member)
528 # recursion
529 self.object_build(child, member)
530 elif inspect.ismethoddescriptor(member):
531 child: nodes.NodeNG = object_build_methoddescriptor(node, member)
532 elif inspect.isdatadescriptor(member):
533 child: nodes.NodeNG = object_build_datadescriptor(node, member)
534 elif isinstance(member, tuple(node_classes.CONST_CLS)):
535 # Special case: __hash__ = None overrides ObjectModel for unhashable types.
536 # See https://docs.python.org/3/reference/datamodel.html#object.__hash__
537 if alias in node.special_attributes and not (
538 alias == "__hash__" and member is None
539 ):
540 continue
541 child = nodes.const_factory(member)
542 elif inspect.isroutine(member):
543 # Callables not caught by the isfunction/isbuiltin branches
544 # above, e.g. some method descriptors.
545 child = _build_from_function(node, member, self._module)
546 elif _safe_has_attribute(member, "__all__"):
547 child: nodes.NodeNG = build_module(alias)
548 # recursion
549 self.object_build(child, member)
550 else:
551 # create an empty node so that the name is actually defined
552 child: nodes.NodeNG = build_dummy(member)
553 if child not in node.locals.get(alias, ()):
554 if _would_create_parent_cycle(node, child):
555 # ``child`` was built for another owner and is already an
556 # ancestor of ``node`` (or is ``node`` itself). Classes that
557 # expose themselves or their siblings as attributes -- pyo3
558 # complex enums do -- reach this. Re-parenting would close a
559 # parent loop and make ``root()`` spin forever, so only
560 # register the name.
561 node.set_local(alias, child)
562 else:
563 node.add_local_node(child, alias)
564 return None
566 def imported_member(self, node, member, name: str) -> bool:
567 """verify this is not an imported class or handle it"""
568 # /!\ some classes like ExtensionClass doesn't have a __module__
569 # attribute ! Also, this may trigger an exception on badly built module
570 # (see http://www.logilab.org/ticket/57299 for instance)
571 try:
572 modname = getattr(member, "__module__", None)
573 except TypeError:
574 modname = None
575 if modname is None:
576 if name in {"__new__", "__subclasshook__"}:
577 # Some builtins have no __module__, e.g. object.__new__
578 modname = builtins.__name__
579 else:
580 attach_dummy_node(node, name, member)
581 return True
583 # On PyPy during bootstrapping we infer _io while _module is
584 # builtins. In CPython _io names itself io, see http://bugs.python.org/issue18602
585 # Therefore, this basically checks whether we are not in PyPy.
586 if modname == "_io" and not self._module.__name__ == "builtins":
587 return False
589 real_name = {"gtk": "gtk_gtk"}.get(modname, modname)
591 if real_name != self._module.__name__:
592 # check if it sounds valid and then add an import node, else use a
593 # dummy node
594 try:
595 with (
596 redirect_stderr(io.StringIO()) as stderr,
597 redirect_stdout(io.StringIO()) as stdout,
598 ):
599 getattr(sys.modules[modname], name)
600 stderr_value = stderr.getvalue()
601 stdout_value = stdout.getvalue()
602 if stderr_value or stdout_value:
603 # pylint: disable=import-outside-toplevel
604 import logging
606 logger = logging.getLogger(__name__)
607 if stderr_value:
608 logger.error(
609 "Captured stderr while getting %s from %s:\n%s",
610 name,
611 sys.modules[modname],
612 stderr_value,
613 )
614 if stdout_value:
615 logger.info(
616 "Captured stdout while getting %s from %s:\n%s",
617 name,
618 sys.modules[modname],
619 stdout_value,
620 )
621 except (KeyError, AttributeError):
622 attach_dummy_node(node, name, member)
623 else:
624 attach_import_node(node, modname, name)
625 return True
626 return False
629# astroid bootstrapping ######################################################
631_CONST_PROXY: dict[type, nodes.ClassDef] = {}
634def _set_proxied(const) -> nodes.ClassDef:
635 # TODO : find a nicer way to handle this situation;
636 return _CONST_PROXY[const.value.__class__]
639def _astroid_bootstrapping() -> None:
640 """astroid bootstrapping the builtins module"""
641 # this boot strapping is necessary since we need the Const nodes to
642 # inspect_build builtins, and then we can proxy Const
643 # pylint: disable-next=import-outside-toplevel
644 from astroid.manager import AstroidManager
646 builder = InspectBuilder(AstroidManager())
647 astroid_builtin = builder.inspect_build(builtins)
649 for cls, node_cls in node_classes.CONST_CLS.items():
650 if cls is TYPE_NONE:
651 proxy = build_class("NoneType", astroid_builtin)
652 elif cls is TYPE_NOTIMPLEMENTED:
653 proxy = build_class("NotImplementedType", astroid_builtin)
654 elif cls is TYPE_ELLIPSIS:
655 proxy = build_class("Ellipsis", astroid_builtin)
656 else:
657 proxy = astroid_builtin.getattr(cls.__name__)[0]
658 assert isinstance(proxy, nodes.ClassDef)
659 if cls in (dict, list, set, tuple):
660 node_cls._proxied = proxy
661 else:
662 _CONST_PROXY[cls] = proxy
664 # Set the builtin module as parent for some builtins.
665 nodes.Const._proxied = property(_set_proxied)
667 _GeneratorType = nodes.ClassDef(
668 types.GeneratorType.__name__,
669 lineno=0,
670 col_offset=0,
671 end_lineno=0,
672 end_col_offset=0,
673 parent=astroid_builtin,
674 )
675 astroid_builtin.set_local(_GeneratorType.name, _GeneratorType)
676 generator_doc_node = (
677 nodes.Const(value=types.GeneratorType.__doc__)
678 if types.GeneratorType.__doc__
679 else None
680 )
681 _GeneratorType.postinit(
682 bases=[],
683 body=[],
684 decorators=None,
685 doc_node=generator_doc_node,
686 )
687 bases.Generator._proxied = _GeneratorType
688 builder.object_build(bases.Generator._proxied, types.GeneratorType)
690 if hasattr(types, "AsyncGeneratorType"):
691 _AsyncGeneratorType = nodes.ClassDef(
692 types.AsyncGeneratorType.__name__,
693 lineno=0,
694 col_offset=0,
695 end_lineno=0,
696 end_col_offset=0,
697 parent=astroid_builtin,
698 )
699 astroid_builtin.set_local(_AsyncGeneratorType.name, _AsyncGeneratorType)
700 async_generator_doc_node = (
701 nodes.Const(value=types.AsyncGeneratorType.__doc__)
702 if types.AsyncGeneratorType.__doc__
703 else None
704 )
705 _AsyncGeneratorType.postinit(
706 bases=[],
707 body=[],
708 decorators=None,
709 doc_node=async_generator_doc_node,
710 )
711 bases.AsyncGenerator._proxied = _AsyncGeneratorType
712 builder.object_build(bases.AsyncGenerator._proxied, types.AsyncGeneratorType)
714 if hasattr(types, "UnionType"):
715 _UnionTypeType = nodes.ClassDef(
716 types.UnionType.__name__,
717 lineno=0,
718 col_offset=0,
719 end_lineno=0,
720 end_col_offset=0,
721 parent=astroid_builtin,
722 )
723 union_type_doc_node = (
724 nodes.Const(value=types.UnionType.__doc__)
725 if types.UnionType.__doc__
726 else None
727 )
728 _UnionTypeType.postinit(
729 bases=[],
730 body=[],
731 decorators=None,
732 doc_node=union_type_doc_node,
733 )
734 bases.UnionType._proxied = _UnionTypeType
735 builder.object_build(bases.UnionType._proxied, types.UnionType)
737 builtin_types = (
738 types.GetSetDescriptorType,
739 types.GeneratorType,
740 types.MemberDescriptorType,
741 TYPE_NONE,
742 TYPE_NOTIMPLEMENTED,
743 types.FunctionType,
744 types.MethodType,
745 types.BuiltinFunctionType,
746 types.ModuleType,
747 types.TracebackType,
748 )
749 for _type in builtin_types:
750 if _type.__name__ not in astroid_builtin:
751 klass = nodes.ClassDef(
752 _type.__name__,
753 lineno=0,
754 col_offset=0,
755 end_lineno=0,
756 end_col_offset=0,
757 parent=astroid_builtin,
758 )
759 doc = _type.__doc__ if isinstance(_type.__doc__, str) else None
760 klass.postinit(
761 bases=[],
762 body=[],
763 decorators=None,
764 doc_node=nodes.Const(doc) if doc else None,
765 )
766 builder.object_build(klass, _type)
767 astroid_builtin[_type.__name__] = klass
769 InspectBuilder.bootstrapped = True
771 # pylint: disable-next=import-outside-toplevel
772 from astroid.brain.brain_builtin_inference import on_bootstrap
774 # Instantiates an AstroidBuilder(), which is where
775 # InspectBuilder.bootstrapped is checked, so place after bootstrapped=True.
776 on_bootstrap()