Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/bases.py: 45%
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 # An UnboundMethod can proxy a Lambda (a lambda already bound to an
76 # instance, like ``A().f``, then assigned in another class body) or even
77 # Uninferable, neither of which can carry decorators.
78 target = meth
79 while isinstance(target, UnboundMethod):
80 target = target._proxied
81 if not isinstance(target, nodes.FunctionDef):
82 return False
83 decoratornames = meth.decoratornames(context=context)
84 if PROPERTIES.intersection(decoratornames):
85 return True
86 stripped = {
87 name.split(".")[-1]
88 for name in decoratornames
89 if not isinstance(name, UninferableBase)
90 }
91 # The names are only a guess, and a property-like decorator only makes
92 # sense in a class body: a function elsewhere stays a function.
93 if any(name in stripped for name in POSSIBLE_PROPERTIES) and isinstance(
94 meth.parent.frame(), nodes.ClassDef
95 ):
96 return True
98 if not meth.decorators:
99 return False
100 # Lookup for subclasses of *property*
101 for decorator in meth.decorators.nodes or ():
102 inferred = safe_infer(decorator, context=context)
103 if inferred is None or isinstance(inferred, UninferableBase):
104 continue
105 if isinstance(inferred, nodes.ClassDef):
106 # Check for a class which inherits from a standard property type
107 if any(inferred.is_subtype_of(pclass) for pclass in PROPERTIES):
108 return True
109 for base_class in inferred.bases:
110 # Check for a class which inherits from functools.cached_property
111 # and includes a subscripted type annotation
112 if isinstance(base_class, nodes.Subscript):
113 value = safe_infer(base_class.value, context=context)
114 if not isinstance(value, nodes.ClassDef):
115 continue
116 if value.name != "cached_property":
117 continue
118 module, _ = value.lookup(value.name)
119 if isinstance(module, nodes.Module) and module.name == "functools":
120 return True
121 continue
123 return False
126class Proxy:
127 """A simple proxy object.
129 Note:
131 Subclasses of this object will need a custom __getattr__
132 if new instance attributes are created. See the Const class
133 """
135 _proxied: nodes.ClassDef | nodes.FunctionDef | nodes.Lambda | UnboundMethod
137 def __init__(
138 self,
139 proxied: (
140 nodes.ClassDef | nodes.FunctionDef | nodes.Lambda | UnboundMethod | None
141 ) = None,
142 ) -> None:
143 if proxied is None:
144 # This is a hack to allow calling this __init__ during bootstrapping of
145 # builtin classes and their docstrings.
146 # For Const, Generator, and UnionType nodes the _proxied attribute
147 # is set during bootstrapping
148 # as we first need to build the ClassDef that they can proxy.
149 # Thus, if proxied is None self should be a Const or Generator
150 # as that is the only way _proxied will be correctly set as a ClassDef.
151 assert isinstance(self, (nodes.Const, Generator, UnionType))
152 else:
153 self._proxied = proxied
155 def __getattr__(self, name: str) -> Any:
156 if name == "_proxied":
157 return self.__class__._proxied
158 if name in self.__dict__:
159 return self.__dict__[name]
160 return getattr(self._proxied, name)
162 def infer( # type: ignore[return]
163 self, context: InferenceContext | None = None
164 ) -> collections.abc.Generator[InferenceResult, None, InferenceErrorInfo | None]:
165 yield self
168def _infer_stmts(
169 stmts: Iterable[InferenceResult],
170 context: InferenceContext | None,
171 frame: nodes.NodeNG | BaseInstance | None = None,
172) -> collections.abc.Generator[InferenceResult]:
173 """Return an iterator on statements inferred by each statement in *stmts*."""
174 inferred = False
175 constraint_failed = False
176 if context is not None:
177 name = context.lookupname
178 context = context.clone()
179 if name is not None:
180 constraints = context.constraints.get(name, {})
181 else:
182 constraints = {}
183 else:
184 name = None
185 constraints = {}
186 context = InferenceContext()
188 for stmt in stmts:
189 if isinstance(stmt, UninferableBase):
190 yield stmt
191 inferred = True
192 continue
193 context.lookupname = stmt._infer_name(frame, name)
194 try:
195 stmt_constraints: set[Constraint] = set()
196 for constraint_stmt, potential_constraints in constraints.items():
197 # pylint: disable-next=import-outside-toplevel
198 from astroid.constraint import constraint_applies
200 # Every constraint of the mapping is generated for the same node.
201 (expr,) = {constraint.node for constraint in potential_constraints}
202 if constraint_applies(constraint_stmt, stmt, expr):
203 stmt_constraints.update(potential_constraints)
204 for inf in stmt.infer(context=context):
205 if all(
206 constraint.satisfied_by(inf, context)
207 for constraint in stmt_constraints
208 ):
209 yield inf
210 inferred = True
211 else:
212 constraint_failed = True
213 except NameInferenceError:
214 continue
215 except InferenceError:
216 yield Uninferable
217 inferred = True
219 if not inferred and constraint_failed:
220 yield Uninferable
221 elif not inferred:
222 raise InferenceError(
223 "Inference failed for all members of {stmts!r}.",
224 stmts=stmts,
225 frame=frame,
226 context=context,
227 )
230def _infer_method_result_truth(
231 instance: Instance, method_name: str, context: InferenceContext
232) -> bool | UninferableBase:
233 # Get the method from the instance and try to infer
234 # its return's truth value.
235 meth = next(instance.igetattr(method_name, context=context), None)
236 if meth and hasattr(meth, "infer_call_result"):
237 if not meth.callable():
238 return Uninferable
239 try:
240 context.callcontext = CallContext(args=[], callee=meth)
241 for value in meth.infer_call_result(instance, context=context):
242 if isinstance(value, UninferableBase):
243 return value
244 try:
245 inferred = next(value.infer(context=context))
246 except StopIteration as e:
247 raise InferenceError(context=context) from e
248 return inferred.bool_value()
249 except InferenceError:
250 pass
251 return Uninferable
254class BaseInstance(Proxy):
255 """An instance base class, which provides lookup methods for potential
256 instances.
257 """
259 _proxied: nodes.ClassDef
261 special_attributes: objectmodel.ObjectModel
263 def display_type(self) -> str:
264 return "Instance of"
266 def getattr(
267 self,
268 name: str,
269 context: InferenceContext | None = None,
270 lookupclass: bool = True,
271 ) -> list[InferenceResult]:
272 try:
273 values = self._proxied.instance_attr(name, context)
274 except AttributeInferenceError as exc:
275 if self.special_attributes and name in self.special_attributes:
276 special_attr = self.special_attributes.lookup(name)
277 if not isinstance(special_attr, nodes.Unknown):
278 return [special_attr]
280 if lookupclass:
281 # Class attributes not available through the instance
282 # unless they are explicitly defined.
283 return self._proxied.getattr(name, context, class_context=False)
285 raise AttributeInferenceError(
286 target=self, attribute=name, context=context
287 ) from exc
288 # since we've no context information, return matching class members as
289 # well
290 if lookupclass:
291 try:
292 return values + self._proxied.getattr(
293 name, context, class_context=False
294 )
295 except AttributeInferenceError:
296 pass
297 return values
299 def igetattr(
300 self, name: str, context: InferenceContext | None = None
301 ) -> Iterator[InferenceResult]:
302 """Inferred getattr."""
303 if not context:
304 context = InferenceContext()
305 try:
306 context.lookupname = name
307 # XXX frame should be self._proxied, or not ?
308 get_attr = self.getattr(name, context, lookupclass=False)
309 yield from _infer_stmts(
310 self._wrap_attr(get_attr, context), context, frame=self
311 )
312 except AttributeInferenceError:
313 try:
314 # fallback to class.igetattr since it has some logic to handle
315 # descriptors
316 # But only if the _proxied is the Class.
317 if self._proxied.__class__.__name__ != "ClassDef":
318 raise
319 attrs = self._proxied.igetattr(name, context, class_context=False)
320 yield from self._wrap_attr(attrs, context)
321 except AttributeInferenceError as error:
322 raise InferenceError(**vars(error)) from error
324 def _wrap_attr(
325 self, attrs: Iterable[InferenceResult], context: InferenceContext | None = None
326 ) -> Iterator[InferenceResult]:
327 """Wrap bound methods of attrs in a InstanceMethod proxies."""
328 for attr in attrs:
329 if isinstance(attr, UnboundMethod):
330 if _is_property(attr):
331 yield from attr.infer_call_result(self, context)
332 else:
333 yield BoundMethod(attr, self)
334 elif isinstance(attr, nodes.Lambda):
335 if attr.args.arguments and attr.args.arguments[0].name == "self":
336 yield BoundMethod(attr, self)
337 continue
338 yield attr
339 else:
340 yield attr
342 def infer_call_result(
343 self,
344 caller: SuccessfulInferenceResult | None,
345 context: InferenceContext | None = None,
346 ) -> Iterator[InferenceResult]:
347 """Infer what a class instance is returning when called."""
348 context = bind_context_to_node(context, self)
349 inferred = False
351 for node in self._proxied.igetattr("__call__", context):
352 if isinstance(node, UninferableBase) or not node.callable():
353 continue
354 if isinstance(node, BaseInstance) and node._proxied is self._proxied:
355 inferred = True
356 yield node
357 # Prevent recursion.
358 continue
359 if context.callcontext:
360 # Arguments belong to __call__, not to the instance's class.
361 # The incoming CallContext is shared with the caller.
362 context.callcontext = copy.copy(context.callcontext)
363 context.callcontext.callee = node
364 for res in node.infer_call_result(caller, context):
365 inferred = True
366 yield res
367 if not inferred:
368 raise InferenceError(node=self, caller=caller, context=context)
371class Instance(BaseInstance):
372 """A special node representing a class instance."""
374 special_attributes = objectmodel.InstanceModel()
376 def __init__(self, proxied: nodes.ClassDef | None) -> None:
377 super().__init__(proxied)
379 @decorators.yes_if_nothing_inferred
380 def infer_binary_op(
381 self,
382 opnode: nodes.AugAssign | nodes.BinOp,
383 operator: str,
384 other: InferenceResult,
385 context: InferenceContext,
386 method: SuccessfulInferenceResult,
387 ) -> Generator[InferenceResult]:
388 return method.infer_call_result(self, context)
390 def __repr__(self) -> str:
391 return f"<Instance of {self._proxied.root().name}.{self._proxied.name} at 0x{id(self)}>"
393 def __str__(self) -> str:
394 return f"Instance of {self._proxied.root().name}.{self._proxied.name}"
396 def callable(self) -> bool:
397 try:
398 self._proxied.getattr("__call__", class_context=False)
399 return True
400 except AttributeInferenceError:
401 return False
403 def pytype(self) -> str:
404 return self._proxied.qname()
406 def display_type(self) -> str:
407 return "Instance of"
409 def bool_value(
410 self, context: InferenceContext | None = None
411 ) -> bool | UninferableBase:
412 """Infer the truth value for an Instance.
414 The truth value of an instance is determined by these conditions:
416 * if it implements __bool__, then its bool value will be
417 determined by calling this special method and checking
418 its result.
419 * when this method is not defined, __len__() is called, if it
420 is defined, and the object is considered true if its result is
421 nonzero. If a class defines neither __len__() nor __bool__(),
422 all its instances are considered true.
423 """
424 context = context or InferenceContext()
425 context.boundnode = self
427 try:
428 result = _infer_method_result_truth(self, "__bool__", context)
429 except (InferenceError, AttributeInferenceError):
430 # Fallback to __len__.
431 try:
432 result = _infer_method_result_truth(self, "__len__", context)
433 except (AttributeInferenceError, InferenceError):
434 return True
435 return result
437 def getitem(
438 self, index: nodes.Const, context: InferenceContext | None = None
439 ) -> InferenceResult | None:
440 new_context = bind_context_to_node(context, self)
441 if not context:
442 context = new_context
443 method = next(self.igetattr("__getitem__", context=context), None)
444 # Create a new CallContext for providing index as an argument.
445 new_context.callcontext = CallContext(args=[index], callee=method)
446 if not isinstance(method, BoundMethod):
447 raise InferenceError(
448 "Could not find __getitem__ for {node!r}.", node=self, context=context
449 )
450 if len(method.args.arguments) != 2: # (self, index)
451 raise AstroidTypeError(
452 "__getitem__ for {node!r} does not have correct signature",
453 node=self,
454 context=context,
455 )
456 return next(method.infer_call_result(self, new_context), None)
459class UnboundMethod(Proxy):
460 """A special node representing a method not bound to an instance."""
462 _proxied: nodes.FunctionDef | nodes.Lambda | UnboundMethod | UninferableBase
464 special_attributes: (
465 objectmodel.BoundMethodModel | objectmodel.UnboundMethodModel
466 ) = objectmodel.UnboundMethodModel()
468 def __repr__(self) -> str:
469 assert self._proxied.parent, "Expected a parent node"
470 frame = self._proxied.parent.frame()
471 return f"<{self.__class__.__name__} {self._proxied.name} of {frame.qname()} at 0x{id(self)}"
473 def implicit_parameters(self) -> Literal[0, 1]:
474 return 0
476 def is_bound(self) -> bool:
477 return False
479 def getattr(self, name: str, context: InferenceContext | None = None):
480 if name in self.special_attributes:
481 special_attr = self.special_attributes.lookup(name)
482 if not isinstance(special_attr, nodes.Unknown):
483 return [special_attr]
484 return self._proxied.getattr(name, context)
486 def igetattr(
487 self, name: str, context: InferenceContext | None = None
488 ) -> Iterator[InferenceResult]:
489 if name in self.special_attributes:
490 special_attr = self.special_attributes.lookup(name)
491 if not isinstance(special_attr, nodes.Unknown):
492 return iter((special_attr,))
493 return self._proxied.igetattr(name, context)
495 def infer_call_result(
496 self,
497 caller: SuccessfulInferenceResult | None,
498 context: InferenceContext | None = None,
499 ) -> Iterator[InferenceResult]:
500 """
501 The boundnode of the regular context with a function called
502 on ``object.__new__`` will be of type ``object``,
503 which is incorrect for the argument in general.
504 If no context is given the ``object.__new__`` call argument will
505 be correctly inferred except when inside a call that requires
506 the additional context (such as a classmethod) of the boundnode
507 to determine which class the method was called from
508 """
510 # If we're unbound method __new__ of a builtin, the result is an
511 # instance of the class given as first argument.
512 if self._proxied.name == "__new__":
513 assert self._proxied.parent, "Expected a parent node"
514 qname = self._proxied.parent.frame().qname()
515 # Avoid checking builtins.type: _infer_type_new_call() does more validation
516 if qname.startswith("builtins.") and qname != "builtins.type":
517 return self._infer_builtin_new(caller, context or InferenceContext())
518 return self._proxied.infer_call_result(caller, context)
520 def _infer_builtin_new(
521 self,
522 caller: SuccessfulInferenceResult | None,
523 context: InferenceContext,
524 ) -> collections.abc.Generator[nodes.Const | Instance | UninferableBase]:
525 if not isinstance(caller, nodes.Call):
526 return
527 if not caller.args:
528 return
529 # Attempt to create a constant
530 if len(caller.args) > 1:
531 value = None
532 if isinstance(caller.args[1], nodes.Const):
533 value = caller.args[1].value
534 else:
535 inferred_arg = next(caller.args[1].infer(), None)
536 if isinstance(inferred_arg, nodes.Const):
537 value = inferred_arg.value
538 if value is not None:
539 const = nodes.const_factory(value)
540 assert not isinstance(const, nodes.EmptyNode)
541 yield const
542 return
544 node_context = context.extra_context.get(caller.args[0])
545 for inferred in caller.args[0].infer(context=node_context):
546 if isinstance(inferred, UninferableBase):
547 yield inferred
548 if isinstance(inferred, nodes.ClassDef):
549 yield Instance(inferred)
550 raise InferenceError
552 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
553 return True
556class BoundMethod(UnboundMethod):
557 """A special node representing a method bound to an instance."""
559 special_attributes = objectmodel.BoundMethodModel()
561 def __init__(
562 self,
563 proxy: nodes.FunctionDef | nodes.Lambda | UnboundMethod,
564 bound: SuccessfulInferenceResult,
565 original_caller: SuccessfulInferenceResult | None = None,
566 ) -> None:
567 super().__init__(proxy)
568 self.bound = bound
569 # For super() calls: the actual instance/class that called super()
570 # Used to correctly infer return type of methods returning Self
571 self.original_caller = original_caller
573 def implicit_parameters(self) -> Literal[0, 1]:
574 if self.name == "__new__":
575 # __new__ acts as a classmethod but the class argument is not implicit.
576 return 0
577 return 1
579 def is_bound(self) -> Literal[True]:
580 return True
582 def _infer_type_new_call(
583 self, caller: nodes.Call, context: InferenceContext
584 ) -> nodes.ClassDef | None: # noqa: C901
585 """Try to infer what type.__new__(mcs, name, bases, attrs) returns.
587 In order for such call to be valid, the metaclass needs to be
588 a subtype of ``type``, the name needs to be a string, the bases
589 needs to be a tuple of classes
590 """
591 # pylint: disable=import-outside-toplevel; circular import
592 from astroid.nodes import Pass
594 # Verify the metaclass
595 try:
596 mcs = next(caller.args[0].infer(context=context))
597 except StopIteration as e:
598 raise InferenceError(context=context) from e
599 if not isinstance(mcs, nodes.ClassDef):
600 # Not a valid first argument.
601 raise InferenceError(
602 "type.__new__() requires a class for metaclass", context=context
603 )
604 if not mcs.is_subtype_of("builtins.type"):
605 # Not a valid metaclass.
606 raise InferenceError(
607 "type.__new__() metaclass must be a subclass of type", context=context
608 )
610 # Verify the name
611 try:
612 name = next(caller.args[1].infer(context=context))
613 except StopIteration as e:
614 raise InferenceError(context=context) from e
615 if not isinstance(name, nodes.Const):
616 # Not a valid name, needs to be a const.
617 raise InferenceError(
618 "type.__new__() requires a constant for name", context=context
619 )
620 if not isinstance(name.value, str):
621 # Needs to be a string.
622 raise InferenceError(
623 "type.__new__() requires a string for name", context=context
624 )
626 # Verify the bases
627 try:
628 bases = next(caller.args[2].infer(context=context))
629 except StopIteration as e:
630 raise InferenceError(context=context) from e
631 if not isinstance(bases, nodes.Tuple):
632 # Needs to be a tuple.
633 raise InferenceError(
634 "type.__new__() requires a tuple for bases", context=context
635 )
636 try:
637 inferred_bases = [next(elt.infer(context=context)) for elt in bases.elts]
638 except StopIteration as e:
639 raise InferenceError(context=context) from e
640 if any(not isinstance(base, nodes.ClassDef) for base in inferred_bases):
641 # All the bases needs to be Classes
642 raise InferenceError(
643 "type.__new__() requires classes for bases", context=context
644 )
646 # Verify the attributes.
647 try:
648 attrs = next(caller.args[3].infer(context=context))
649 except StopIteration as e:
650 raise InferenceError(context=context) from e
651 if not isinstance(attrs, nodes.Dict):
652 # Needs to be a dictionary.
653 raise InferenceError(
654 "type.__new__() requires a dict for attrs", context=context
655 )
656 cls_locals: dict[str, list[InferenceResult]] = collections.defaultdict(list)
657 for key, value in attrs.items:
658 try:
659 key = next(key.infer(context=context))
660 except StopIteration as e:
661 raise InferenceError(context=context) from e
662 try:
663 value = next(value.infer(context=context))
664 except StopIteration as e:
665 raise InferenceError(context=context) from e
666 # Ignore non string keys
667 if isinstance(key, nodes.Const) and isinstance(key.value, str):
668 cls_locals[key.value].append(value)
670 # Build the class from now.
671 cls = mcs.__class__(
672 name=name.value,
673 lineno=caller.lineno or 0,
674 col_offset=caller.col_offset or 0,
675 parent=caller,
676 end_lineno=caller.end_lineno,
677 end_col_offset=caller.end_col_offset,
678 )
679 empty = Pass(
680 parent=cls,
681 lineno=caller.lineno,
682 col_offset=caller.col_offset,
683 end_lineno=caller.end_lineno,
684 end_col_offset=caller.end_col_offset,
685 )
686 cls.postinit(
687 bases=bases.elts,
688 body=[empty],
689 decorators=None,
690 metaclass=mcs,
691 keywords=[],
692 )
693 cls.locals = cls_locals
694 return cls
696 def infer_call_result(
697 self,
698 caller: SuccessfulInferenceResult | None,
699 context: InferenceContext | None = None,
700 ) -> Iterator[InferenceResult]:
701 # For super() calls, use original_caller to correctly infer Self return type
702 bound_node = self.original_caller if self.original_caller else self.bound
703 context = bind_context_to_node(context, bound_node)
704 if (
705 isinstance(self.bound, nodes.ClassDef)
706 and self.bound.name == "type"
707 and self.name == "__new__"
708 and isinstance(caller, nodes.Call)
709 ):
710 # Check if we have a ``type.__new__(mcs, name, bases, attrs)`` call.
711 if len(caller.args) != 4:
712 raise InferenceError(
713 f"type.__new__() requires 4 arguments, got {len(caller.args)}",
714 context=context,
715 )
716 new_cls = self._infer_type_new_call(caller, context)
717 if new_cls:
718 return iter((new_cls,))
720 return super().infer_call_result(caller, context)
722 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
723 return True
726class Generator(BaseInstance):
727 """A special node representing a generator.
729 Proxied class is set once for all in raw_building.
730 """
732 # We defer initialization of special_attributes to the __init__ method since the constructor
733 # of GeneratorModel requires the raw_building to be complete
734 # TODO: This should probably be refactored.
735 special_attributes: objectmodel.GeneratorBaseModel
737 def __init__(
738 self,
739 parent: nodes.FunctionDef,
740 generator_initial_context: InferenceContext | None = None,
741 ) -> None:
742 super().__init__()
743 self.parent = parent
744 self._call_context = copy_context(generator_initial_context)
746 # See comment above: this is a deferred initialization.
747 Generator.special_attributes = objectmodel.GeneratorModel()
749 def infer_yield_types(self) -> Iterator[InferenceResult]:
750 yield from self.parent.infer_yield_result(self._call_context)
752 def callable(self) -> Literal[False]:
753 return False
755 def pytype(self) -> str:
756 return "builtins.generator"
758 def display_type(self) -> str:
759 return "Generator"
761 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
762 return True
764 def __repr__(self) -> str:
765 return f"<Generator({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>"
767 def __str__(self) -> str:
768 return f"Generator({self._proxied.name})"
771class AsyncGenerator(Generator):
772 """Special node representing an async generator."""
774 def __init__(self, *args, **kwargs):
775 super().__init__(*args, **kwargs)
776 AsyncGenerator.special_attributes = objectmodel.AsyncGeneratorModel()
778 def pytype(self) -> Literal["builtins.async_generator"]:
779 return "builtins.async_generator"
781 def display_type(self) -> str:
782 return "AsyncGenerator"
784 def __repr__(self) -> str:
785 return f"<AsyncGenerator({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>"
787 def __str__(self) -> str:
788 return f"AsyncGenerator({self._proxied.name})"
791class UnionType(BaseInstance):
792 """Special node representing new style typing unions.
794 Proxied class is set once for all in raw_building.
795 """
797 def __init__(
798 self,
799 left: UnionType | nodes.ClassDef | nodes.Const,
800 right: UnionType | nodes.ClassDef | nodes.Const,
801 parent: nodes.NodeNG | None = None,
802 ) -> None:
803 super().__init__()
804 self.parent = parent
805 self.left = left
806 self.right = right
808 def callable(self) -> Literal[False]:
809 return False
811 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
812 return True
814 def pytype(self) -> Literal["types.UnionType"]:
815 return "types.UnionType"
817 def display_type(self) -> str:
818 return "UnionType"
820 def __repr__(self) -> str:
821 return f"<UnionType({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>"
823 def __str__(self) -> str:
824 return f"UnionType({self._proxied.name})"