Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/bases.py: 42%
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 base classes and functions for the nodes and some
6inference utils.
7"""
9from __future__ import annotations
11import collections
12import collections.abc
13import copy
14from collections.abc import Iterable, Iterator
15from typing import TYPE_CHECKING, Any, Literal
17from astroid import decorators, nodes
18from astroid.context import (
19 CallContext,
20 InferenceContext,
21 bind_context_to_node,
22 copy_context,
23)
24from astroid.exceptions import (
25 AstroidTypeError,
26 AttributeInferenceError,
27 InferenceError,
28 NameInferenceError,
29)
30from astroid.interpreter import objectmodel
31from astroid.typing import (
32 InferenceErrorInfo,
33 InferenceResult,
34 SuccessfulInferenceResult,
35)
36from astroid.util import Uninferable, UninferableBase, safe_infer
38if TYPE_CHECKING:
39 from astroid.constraint import Constraint
42PROPERTIES = {
43 "builtins.property",
44 "abc.abstractproperty",
45 "functools.cached_property",
46 "enum.property",
47}
49# List of possible property names. We use this list in order
50# to see if a method is a property or not. This should be
51# pretty reliable and fast, the alternative being to check each
52# decorator to see if its a real property-like descriptor, which
53# can be too complicated.
54# Also, these aren't qualified, because each project can
55# define them, we shouldn't expect to know every possible
56# property-like decorator!
57POSSIBLE_PROPERTIES = {
58 "cached_property",
59 "cachedproperty",
60 "lazyproperty",
61 "lazy_property",
62 "reify",
63 "lazyattribute",
64 "lazy_attribute",
65 "LazyProperty",
66 "lazy",
67 "cache_readonly",
68 "DynamicClassAttribute",
69}
72def _is_property(
73 meth: nodes.FunctionDef | UnboundMethod, context: InferenceContext | None = None
74) -> bool:
75 decoratornames = meth.decoratornames(context=context)
76 if PROPERTIES.intersection(decoratornames):
77 return True
78 stripped = {
79 name.split(".")[-1]
80 for name in decoratornames
81 if not isinstance(name, UninferableBase)
82 }
83 if any(name in stripped for name in POSSIBLE_PROPERTIES):
84 return True
86 if not meth.decorators:
87 return False
88 # Lookup for subclasses of *property*
89 for decorator in meth.decorators.nodes or ():
90 inferred = safe_infer(decorator, context=context)
91 if inferred is None or isinstance(inferred, UninferableBase):
92 continue
93 if isinstance(inferred, nodes.ClassDef):
94 # Check for a class which inherits from a standard property type
95 if any(inferred.is_subtype_of(pclass) for pclass in PROPERTIES):
96 return True
97 for base_class in inferred.bases:
98 # Check for a class which inherits from functools.cached_property
99 # and includes a subscripted type annotation
100 if isinstance(base_class, nodes.Subscript):
101 value = safe_infer(base_class.value, context=context)
102 if not isinstance(value, nodes.ClassDef):
103 continue
104 if value.name != "cached_property":
105 continue
106 module, _ = value.lookup(value.name)
107 if isinstance(module, nodes.Module) and module.name == "functools":
108 return True
109 continue
111 return False
114class Proxy:
115 """A simple proxy object.
117 Note:
119 Subclasses of this object will need a custom __getattr__
120 if new instance attributes are created. See the Const class
121 """
123 _proxied: nodes.ClassDef | nodes.FunctionDef | nodes.Lambda | UnboundMethod
125 def __init__(
126 self,
127 proxied: (
128 nodes.ClassDef | nodes.FunctionDef | nodes.Lambda | UnboundMethod | None
129 ) = None,
130 ) -> None:
131 if proxied is None:
132 # This is a hack to allow calling this __init__ during bootstrapping of
133 # builtin classes and their docstrings.
134 # For Const, Generator, and UnionType nodes the _proxied attribute
135 # is set during bootstrapping
136 # as we first need to build the ClassDef that they can proxy.
137 # Thus, if proxied is None self should be a Const or Generator
138 # as that is the only way _proxied will be correctly set as a ClassDef.
139 assert isinstance(self, (nodes.Const, Generator, UnionType))
140 else:
141 self._proxied = proxied
143 def __getattr__(self, name: str) -> Any:
144 if name == "_proxied":
145 return self.__class__._proxied
146 if name in self.__dict__:
147 return self.__dict__[name]
148 return getattr(self._proxied, name)
150 def infer( # type: ignore[return]
151 self, context: InferenceContext | None = None
152 ) -> collections.abc.Generator[InferenceResult, None, InferenceErrorInfo | None]:
153 yield self
156def _infer_stmts(
157 stmts: Iterable[InferenceResult],
158 context: InferenceContext | None,
159 frame: nodes.NodeNG | BaseInstance | None = None,
160) -> collections.abc.Generator[InferenceResult]:
161 """Return an iterator on statements inferred by each statement in *stmts*."""
162 inferred = False
163 constraint_failed = False
164 if context is not None:
165 name = context.lookupname
166 context = context.clone()
167 if name is not None:
168 constraints = context.constraints.get(name, {})
169 else:
170 constraints = {}
171 else:
172 name = None
173 constraints = {}
174 context = InferenceContext()
176 for stmt in stmts:
177 if isinstance(stmt, UninferableBase):
178 yield stmt
179 inferred = True
180 continue
181 context.lookupname = stmt._infer_name(frame, name)
182 try:
183 stmt_constraints: set[Constraint] = set()
184 for constraint_stmt, potential_constraints in constraints.items():
185 # pylint: disable-next=import-outside-toplevel
186 from astroid.constraint import constraint_applies
188 # Every constraint of the mapping is generated for the same node.
189 (expr,) = {constraint.node for constraint in potential_constraints}
190 if constraint_applies(constraint_stmt, stmt, expr):
191 stmt_constraints.update(potential_constraints)
192 for inf in stmt.infer(context=context):
193 if all(
194 constraint.satisfied_by(inf, context)
195 for constraint in stmt_constraints
196 ):
197 yield inf
198 inferred = True
199 else:
200 constraint_failed = True
201 except NameInferenceError:
202 continue
203 except InferenceError:
204 yield Uninferable
205 inferred = True
207 if not inferred and constraint_failed:
208 yield Uninferable
209 elif not inferred:
210 raise InferenceError(
211 "Inference failed for all members of {stmts!r}.",
212 stmts=stmts,
213 frame=frame,
214 context=context,
215 )
218def _infer_method_result_truth(
219 instance: Instance, method_name: str, context: InferenceContext
220) -> bool | UninferableBase:
221 # Get the method from the instance and try to infer
222 # its return's truth value.
223 meth = next(instance.igetattr(method_name, context=context), None)
224 if meth and hasattr(meth, "infer_call_result"):
225 if not meth.callable():
226 return Uninferable
227 try:
228 context.callcontext = CallContext(args=[], callee=meth)
229 for value in meth.infer_call_result(instance, context=context):
230 if isinstance(value, UninferableBase):
231 return value
232 try:
233 inferred = next(value.infer(context=context))
234 except StopIteration as e:
235 raise InferenceError(context=context) from e
236 return inferred.bool_value()
237 except InferenceError:
238 pass
239 return Uninferable
242class BaseInstance(Proxy):
243 """An instance base class, which provides lookup methods for potential
244 instances.
245 """
247 _proxied: nodes.ClassDef
249 special_attributes: objectmodel.ObjectModel
251 def display_type(self) -> str:
252 return "Instance of"
254 def getattr(
255 self,
256 name: str,
257 context: InferenceContext | None = None,
258 lookupclass: bool = True,
259 ) -> list[InferenceResult]:
260 try:
261 values = self._proxied.instance_attr(name, context)
262 except AttributeInferenceError as exc:
263 if self.special_attributes and name in self.special_attributes:
264 special_attr = self.special_attributes.lookup(name)
265 if not isinstance(special_attr, nodes.Unknown):
266 return [special_attr]
268 if lookupclass:
269 # Class attributes not available through the instance
270 # unless they are explicitly defined.
271 return self._proxied.getattr(name, context, class_context=False)
273 raise AttributeInferenceError(
274 target=self, attribute=name, context=context
275 ) from exc
276 # since we've no context information, return matching class members as
277 # well
278 if lookupclass:
279 try:
280 return values + self._proxied.getattr(
281 name, context, class_context=False
282 )
283 except AttributeInferenceError:
284 pass
285 return values
287 def igetattr(
288 self, name: str, context: InferenceContext | None = None
289 ) -> Iterator[InferenceResult]:
290 """Inferred getattr."""
291 if not context:
292 context = InferenceContext()
293 try:
294 context.lookupname = name
295 # XXX frame should be self._proxied, or not ?
296 get_attr = self.getattr(name, context, lookupclass=False)
297 yield from _infer_stmts(
298 self._wrap_attr(get_attr, context), context, frame=self
299 )
300 except AttributeInferenceError:
301 try:
302 # fallback to class.igetattr since it has some logic to handle
303 # descriptors
304 # But only if the _proxied is the Class.
305 if self._proxied.__class__.__name__ != "ClassDef":
306 raise
307 attrs = self._proxied.igetattr(name, context, class_context=False)
308 yield from self._wrap_attr(attrs, context)
309 except AttributeInferenceError as error:
310 raise InferenceError(**vars(error)) from error
312 def _wrap_attr(
313 self, attrs: Iterable[InferenceResult], context: InferenceContext | None = None
314 ) -> Iterator[InferenceResult]:
315 """Wrap bound methods of attrs in a InstanceMethod proxies."""
316 for attr in attrs:
317 if isinstance(attr, UnboundMethod):
318 if _is_property(attr):
319 yield from attr.infer_call_result(self, context)
320 else:
321 yield BoundMethod(attr, self)
322 elif isinstance(attr, nodes.Lambda):
323 if attr.args.arguments and attr.args.arguments[0].name == "self":
324 yield BoundMethod(attr, self)
325 continue
326 yield attr
327 else:
328 yield attr
330 def infer_call_result(
331 self,
332 caller: SuccessfulInferenceResult | None,
333 context: InferenceContext | None = None,
334 ) -> Iterator[InferenceResult]:
335 """Infer what a class instance is returning when called."""
336 context = bind_context_to_node(context, self)
337 inferred = False
339 for node in self._proxied.igetattr("__call__", context):
340 if isinstance(node, UninferableBase) or not node.callable():
341 continue
342 if isinstance(node, BaseInstance) and node._proxied is self._proxied:
343 inferred = True
344 yield node
345 # Prevent recursion.
346 continue
347 if context.callcontext:
348 # Arguments belong to __call__, not to the instance's class.
349 # The incoming CallContext is shared with the caller.
350 context.callcontext = copy.copy(context.callcontext)
351 context.callcontext.callee = node
352 for res in node.infer_call_result(caller, context):
353 inferred = True
354 yield res
355 if not inferred:
356 raise InferenceError(node=self, caller=caller, context=context)
359class Instance(BaseInstance):
360 """A special node representing a class instance."""
362 special_attributes = objectmodel.InstanceModel()
364 def __init__(self, proxied: nodes.ClassDef | None) -> None:
365 super().__init__(proxied)
367 @decorators.yes_if_nothing_inferred
368 def infer_binary_op(
369 self,
370 opnode: nodes.AugAssign | nodes.BinOp,
371 operator: str,
372 other: InferenceResult,
373 context: InferenceContext,
374 method: SuccessfulInferenceResult,
375 ) -> Generator[InferenceResult]:
376 return method.infer_call_result(self, context)
378 def __repr__(self) -> str:
379 return f"<Instance of {self._proxied.root().name}.{self._proxied.name} at 0x{id(self)}>"
381 def __str__(self) -> str:
382 return f"Instance of {self._proxied.root().name}.{self._proxied.name}"
384 def callable(self) -> bool:
385 try:
386 self._proxied.getattr("__call__", class_context=False)
387 return True
388 except AttributeInferenceError:
389 return False
391 def pytype(self) -> str:
392 return self._proxied.qname()
394 def display_type(self) -> str:
395 return "Instance of"
397 def bool_value(
398 self, context: InferenceContext | None = None
399 ) -> bool | UninferableBase:
400 """Infer the truth value for an Instance.
402 The truth value of an instance is determined by these conditions:
404 * if it implements __bool__, then its bool value will be
405 determined by calling this special method and checking
406 its result.
407 * when this method is not defined, __len__() is called, if it
408 is defined, and the object is considered true if its result is
409 nonzero. If a class defines neither __len__() nor __bool__(),
410 all its instances are considered true.
411 """
412 context = context or InferenceContext()
413 context.boundnode = self
415 try:
416 result = _infer_method_result_truth(self, "__bool__", context)
417 except (InferenceError, AttributeInferenceError):
418 # Fallback to __len__.
419 try:
420 result = _infer_method_result_truth(self, "__len__", context)
421 except (AttributeInferenceError, InferenceError):
422 return True
423 return result
425 def getitem(
426 self, index: nodes.Const, context: InferenceContext | None = None
427 ) -> InferenceResult | None:
428 new_context = bind_context_to_node(context, self)
429 if not context:
430 context = new_context
431 method = next(self.igetattr("__getitem__", context=context), None)
432 # Create a new CallContext for providing index as an argument.
433 new_context.callcontext = CallContext(args=[index], callee=method)
434 if not isinstance(method, BoundMethod):
435 raise InferenceError(
436 "Could not find __getitem__ for {node!r}.", node=self, context=context
437 )
438 if len(method.args.arguments) != 2: # (self, index)
439 raise AstroidTypeError(
440 "__getitem__ for {node!r} does not have correct signature",
441 node=self,
442 context=context,
443 )
444 return next(method.infer_call_result(self, new_context), None)
447class UnboundMethod(Proxy):
448 """A special node representing a method not bound to an instance."""
450 _proxied: nodes.FunctionDef | UnboundMethod
452 special_attributes: (
453 objectmodel.BoundMethodModel | objectmodel.UnboundMethodModel
454 ) = objectmodel.UnboundMethodModel()
456 def __repr__(self) -> str:
457 assert self._proxied.parent, "Expected a parent node"
458 frame = self._proxied.parent.frame()
459 return f"<{self.__class__.__name__} {self._proxied.name} of {frame.qname()} at 0x{id(self)}"
461 def implicit_parameters(self) -> Literal[0, 1]:
462 return 0
464 def is_bound(self) -> bool:
465 return False
467 def getattr(self, name: str, context: InferenceContext | None = None):
468 if name in self.special_attributes:
469 special_attr = self.special_attributes.lookup(name)
470 if not isinstance(special_attr, nodes.Unknown):
471 return [special_attr]
472 return self._proxied.getattr(name, context)
474 def igetattr(
475 self, name: str, context: InferenceContext | None = None
476 ) -> Iterator[InferenceResult]:
477 if name in self.special_attributes:
478 special_attr = self.special_attributes.lookup(name)
479 if not isinstance(special_attr, nodes.Unknown):
480 return iter((special_attr,))
481 return self._proxied.igetattr(name, context)
483 def infer_call_result(
484 self,
485 caller: SuccessfulInferenceResult | None,
486 context: InferenceContext | None = None,
487 ) -> Iterator[InferenceResult]:
488 """
489 The boundnode of the regular context with a function called
490 on ``object.__new__`` will be of type ``object``,
491 which is incorrect for the argument in general.
492 If no context is given the ``object.__new__`` call argument will
493 be correctly inferred except when inside a call that requires
494 the additional context (such as a classmethod) of the boundnode
495 to determine which class the method was called from
496 """
498 # If we're unbound method __new__ of a builtin, the result is an
499 # instance of the class given as first argument.
500 if self._proxied.name == "__new__":
501 assert self._proxied.parent, "Expected a parent node"
502 qname = self._proxied.parent.frame().qname()
503 # Avoid checking builtins.type: _infer_type_new_call() does more validation
504 if qname.startswith("builtins.") and qname != "builtins.type":
505 return self._infer_builtin_new(caller, context or InferenceContext())
506 return self._proxied.infer_call_result(caller, context)
508 def _infer_builtin_new(
509 self,
510 caller: SuccessfulInferenceResult | None,
511 context: InferenceContext,
512 ) -> collections.abc.Generator[nodes.Const | Instance | UninferableBase]:
513 if not isinstance(caller, nodes.Call):
514 return
515 if not caller.args:
516 return
517 # Attempt to create a constant
518 if len(caller.args) > 1:
519 value = None
520 if isinstance(caller.args[1], nodes.Const):
521 value = caller.args[1].value
522 else:
523 inferred_arg = next(caller.args[1].infer(), None)
524 if isinstance(inferred_arg, nodes.Const):
525 value = inferred_arg.value
526 if value is not None:
527 const = nodes.const_factory(value)
528 assert not isinstance(const, nodes.EmptyNode)
529 yield const
530 return
532 node_context = context.extra_context.get(caller.args[0])
533 for inferred in caller.args[0].infer(context=node_context):
534 if isinstance(inferred, UninferableBase):
535 yield inferred
536 if isinstance(inferred, nodes.ClassDef):
537 yield Instance(inferred)
538 raise InferenceError
540 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
541 return True
544class BoundMethod(UnboundMethod):
545 """A special node representing a method bound to an instance."""
547 special_attributes = objectmodel.BoundMethodModel()
549 def __init__(
550 self,
551 proxy: nodes.FunctionDef | nodes.Lambda | UnboundMethod,
552 bound: SuccessfulInferenceResult,
553 original_caller: SuccessfulInferenceResult | None = None,
554 ) -> None:
555 super().__init__(proxy)
556 self.bound = bound
557 # For super() calls: the actual instance/class that called super()
558 # Used to correctly infer return type of methods returning Self
559 self.original_caller = original_caller
561 def implicit_parameters(self) -> Literal[0, 1]:
562 if self.name == "__new__":
563 # __new__ acts as a classmethod but the class argument is not implicit.
564 return 0
565 return 1
567 def is_bound(self) -> Literal[True]:
568 return True
570 def _infer_type_new_call(
571 self, caller: nodes.Call, context: InferenceContext
572 ) -> nodes.ClassDef | None: # noqa: C901
573 """Try to infer what type.__new__(mcs, name, bases, attrs) returns.
575 In order for such call to be valid, the metaclass needs to be
576 a subtype of ``type``, the name needs to be a string, the bases
577 needs to be a tuple of classes
578 """
579 # pylint: disable=import-outside-toplevel; circular import
580 from astroid.nodes import Pass
582 # Verify the metaclass
583 try:
584 mcs = next(caller.args[0].infer(context=context))
585 except StopIteration as e:
586 raise InferenceError(context=context) from e
587 if not isinstance(mcs, nodes.ClassDef):
588 # Not a valid first argument.
589 raise InferenceError(
590 "type.__new__() requires a class for metaclass", context=context
591 )
592 if not mcs.is_subtype_of("builtins.type"):
593 # Not a valid metaclass.
594 raise InferenceError(
595 "type.__new__() metaclass must be a subclass of type", context=context
596 )
598 # Verify the name
599 try:
600 name = next(caller.args[1].infer(context=context))
601 except StopIteration as e:
602 raise InferenceError(context=context) from e
603 if not isinstance(name, nodes.Const):
604 # Not a valid name, needs to be a const.
605 raise InferenceError(
606 "type.__new__() requires a constant for name", context=context
607 )
608 if not isinstance(name.value, str):
609 # Needs to be a string.
610 raise InferenceError(
611 "type.__new__() requires a string for name", context=context
612 )
614 # Verify the bases
615 try:
616 bases = next(caller.args[2].infer(context=context))
617 except StopIteration as e:
618 raise InferenceError(context=context) from e
619 if not isinstance(bases, nodes.Tuple):
620 # Needs to be a tuple.
621 raise InferenceError(
622 "type.__new__() requires a tuple for bases", context=context
623 )
624 try:
625 inferred_bases = [next(elt.infer(context=context)) for elt in bases.elts]
626 except StopIteration as e:
627 raise InferenceError(context=context) from e
628 if any(not isinstance(base, nodes.ClassDef) for base in inferred_bases):
629 # All the bases needs to be Classes
630 raise InferenceError(
631 "type.__new__() requires classes for bases", context=context
632 )
634 # Verify the attributes.
635 try:
636 attrs = next(caller.args[3].infer(context=context))
637 except StopIteration as e:
638 raise InferenceError(context=context) from e
639 if not isinstance(attrs, nodes.Dict):
640 # Needs to be a dictionary.
641 raise InferenceError(
642 "type.__new__() requires a dict for attrs", context=context
643 )
644 cls_locals: dict[str, list[InferenceResult]] = collections.defaultdict(list)
645 for key, value in attrs.items:
646 try:
647 key = next(key.infer(context=context))
648 except StopIteration as e:
649 raise InferenceError(context=context) from e
650 try:
651 value = next(value.infer(context=context))
652 except StopIteration as e:
653 raise InferenceError(context=context) from e
654 # Ignore non string keys
655 if isinstance(key, nodes.Const) and isinstance(key.value, str):
656 cls_locals[key.value].append(value)
658 # Build the class from now.
659 cls = mcs.__class__(
660 name=name.value,
661 lineno=caller.lineno or 0,
662 col_offset=caller.col_offset or 0,
663 parent=caller,
664 end_lineno=caller.end_lineno,
665 end_col_offset=caller.end_col_offset,
666 )
667 empty = Pass(
668 parent=cls,
669 lineno=caller.lineno,
670 col_offset=caller.col_offset,
671 end_lineno=caller.end_lineno,
672 end_col_offset=caller.end_col_offset,
673 )
674 cls.postinit(
675 bases=bases.elts,
676 body=[empty],
677 decorators=None,
678 metaclass=mcs,
679 keywords=[],
680 )
681 cls.locals = cls_locals
682 return cls
684 def infer_call_result(
685 self,
686 caller: SuccessfulInferenceResult | None,
687 context: InferenceContext | None = None,
688 ) -> Iterator[InferenceResult]:
689 # For super() calls, use original_caller to correctly infer Self return type
690 bound_node = self.original_caller if self.original_caller else self.bound
691 context = bind_context_to_node(context, bound_node)
692 if (
693 isinstance(self.bound, nodes.ClassDef)
694 and self.bound.name == "type"
695 and self.name == "__new__"
696 and isinstance(caller, nodes.Call)
697 ):
698 # Check if we have a ``type.__new__(mcs, name, bases, attrs)`` call.
699 if len(caller.args) != 4:
700 raise InferenceError(
701 f"type.__new__() requires 4 arguments, got {len(caller.args)}",
702 context=context,
703 )
704 new_cls = self._infer_type_new_call(caller, context)
705 if new_cls:
706 return iter((new_cls,))
708 return super().infer_call_result(caller, context)
710 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
711 return True
714class Generator(BaseInstance):
715 """A special node representing a generator.
717 Proxied class is set once for all in raw_building.
718 """
720 # We defer initialization of special_attributes to the __init__ method since the constructor
721 # of GeneratorModel requires the raw_building to be complete
722 # TODO: This should probably be refactored.
723 special_attributes: objectmodel.GeneratorBaseModel
725 def __init__(
726 self,
727 parent: nodes.FunctionDef,
728 generator_initial_context: InferenceContext | None = None,
729 ) -> None:
730 super().__init__()
731 self.parent = parent
732 self._call_context = copy_context(generator_initial_context)
734 # See comment above: this is a deferred initialization.
735 Generator.special_attributes = objectmodel.GeneratorModel()
737 def infer_yield_types(self) -> Iterator[InferenceResult]:
738 yield from self.parent.infer_yield_result(self._call_context)
740 def callable(self) -> Literal[False]:
741 return False
743 def pytype(self) -> str:
744 return "builtins.generator"
746 def display_type(self) -> str:
747 return "Generator"
749 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
750 return True
752 def __repr__(self) -> str:
753 return f"<Generator({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>"
755 def __str__(self) -> str:
756 return f"Generator({self._proxied.name})"
759class AsyncGenerator(Generator):
760 """Special node representing an async generator."""
762 def __init__(self, *args, **kwargs):
763 super().__init__(*args, **kwargs)
764 AsyncGenerator.special_attributes = objectmodel.AsyncGeneratorModel()
766 def pytype(self) -> Literal["builtins.async_generator"]:
767 return "builtins.async_generator"
769 def display_type(self) -> str:
770 return "AsyncGenerator"
772 def __repr__(self) -> str:
773 return f"<AsyncGenerator({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>"
775 def __str__(self) -> str:
776 return f"AsyncGenerator({self._proxied.name})"
779class UnionType(BaseInstance):
780 """Special node representing new style typing unions.
782 Proxied class is set once for all in raw_building.
783 """
785 def __init__(
786 self,
787 left: UnionType | nodes.ClassDef | nodes.Const,
788 right: UnionType | nodes.ClassDef | nodes.Const,
789 parent: nodes.NodeNG | None = None,
790 ) -> None:
791 super().__init__()
792 self.parent = parent
793 self.left = left
794 self.right = right
796 def callable(self) -> Literal[False]:
797 return False
799 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
800 return True
802 def pytype(self) -> Literal["types.UnionType"]:
803 return "types.UnionType"
805 def display_type(self) -> str:
806 return "UnionType"
808 def __repr__(self) -> str:
809 return f"<UnionType({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>"
811 def __str__(self) -> str:
812 return f"UnionType({self._proxied.name})"