|
18 | 18 | StatementType,
|
19 | 19 | )
|
20 | 20 | from astx.blocks import Block
|
| 21 | +from astx.callables import ( |
| 22 | + Comprehension, |
| 23 | +) |
21 | 24 | from astx.tools.typing import typechecked
|
22 | 25 | from astx.variables import InlineVariableDeclaration
|
23 | 26 |
|
@@ -691,3 +694,60 @@ def get_struct(self, simplified: bool = False) -> ReprStruct:
|
691 | 694 | key = f"GOTO-STMT[{self.label.value}]"
|
692 | 695 | value: DictDataTypesStruct = {}
|
693 | 696 | return self._prepare_struct(key, value, simplified)
|
| 697 | + |
| 698 | + |
| 699 | +@public |
| 700 | +@typechecked |
| 701 | +class DictComprehension(Comprehension): |
| 702 | + """AST node for dictionary comprehensions.""" |
| 703 | + |
| 704 | + key: Expr |
| 705 | + value: Expr |
| 706 | + |
| 707 | + def __init__( |
| 708 | + self, |
| 709 | + key: Expr, |
| 710 | + value: Expr, |
| 711 | + iterable: Expr, |
| 712 | + conditions: Optional[list[Expr]] = None, |
| 713 | + is_async: bool = False, |
| 714 | + loc: SourceLocation = NO_SOURCE_LOCATION, |
| 715 | + parent: Optional[ASTNodes] = None, |
| 716 | + ) -> None: |
| 717 | + super().__init__( |
| 718 | + target=key, |
| 719 | + iterable=iterable, |
| 720 | + conditions=conditions, |
| 721 | + is_async=is_async, |
| 722 | + loc=loc, |
| 723 | + parent=parent, |
| 724 | + ) |
| 725 | + self.key = key |
| 726 | + self.value = value |
| 727 | + self.kind = ASTKind.DictComprehensionKind |
| 728 | + |
| 729 | + def __str__(self) -> str: |
| 730 | + """Return a string representation of the object.""" |
| 731 | + ret_str = ( |
| 732 | + f"{{{self.key}: {self.value} for {self.key} in {self.iterable}" |
| 733 | + ) |
| 734 | + if self.conditions is not None: |
| 735 | + for cond in self.conditions: |
| 736 | + ret_str += f" if {cond}" |
| 737 | + ret_str += "}" |
| 738 | + return ret_str |
| 739 | + |
| 740 | + def get_struct(self, simplified: bool = False) -> ReprStruct: |
| 741 | + """Return the AST structure of the object.""" |
| 742 | + value: ReprStruct = { |
| 743 | + "key": self.key.get_struct(simplified), |
| 744 | + "value": self.value.get_struct(simplified), |
| 745 | + "iterable": self.iterable.get_struct(simplified), |
| 746 | + "conditions": cast( |
| 747 | + ReprStruct, |
| 748 | + [cond.get_struct(simplified) for cond in self.conditions], |
| 749 | + ), |
| 750 | + } |
| 751 | + |
| 752 | + key = "DICT-COMPREHENSION" |
| 753 | + return self._prepare_struct(key, value, simplified) |
0 commit comments