|
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 |
|
@@ -737,3 +740,71 @@ def __init__(
|
737 | 740 | def __str__(self) -> str:
|
738 | 741 | """Return a string representation of the object."""
|
739 | 742 | return f"DoWhileExpr[{self.condition}]"
|
| 743 | + |
| 744 | + |
| 745 | +@public |
| 746 | +@typechecked |
| 747 | +class DictComprehension(Comprehension): |
| 748 | + """AST node for dictionary comprehensions.""" |
| 749 | + |
| 750 | + key: Expr |
| 751 | + value: Expr |
| 752 | + |
| 753 | + def __init__( |
| 754 | + self, |
| 755 | + key: Expr, |
| 756 | + value: Expr, |
| 757 | + target: Expr, |
| 758 | + iterable: Expr, |
| 759 | + conditions: Optional[list[Expr]] = None, |
| 760 | + is_async: bool = False, |
| 761 | + loc: SourceLocation = NO_SOURCE_LOCATION, |
| 762 | + parent: Optional[ASTNodes] = None, |
| 763 | + ) -> None: |
| 764 | + super().__init__( |
| 765 | + target=target, |
| 766 | + iterable=iterable, |
| 767 | + conditions=conditions, |
| 768 | + is_async=is_async, |
| 769 | + loc=loc, |
| 770 | + parent=parent, |
| 771 | + ) |
| 772 | + self.key = key |
| 773 | + self.value = value |
| 774 | + self.kind = ASTKind.DictComprehensionKind |
| 775 | + |
| 776 | + def __str__(self) -> str: |
| 777 | + """Return a string representation of the object.""" |
| 778 | + ret_str = ( |
| 779 | + f"DictComprehension[key={self.key}, value={self.value}," |
| 780 | + f" target={self.target}, iterable={self.iterable}," |
| 781 | + ) |
| 782 | + if self.conditions is not None: |
| 783 | + cons_list = [] |
| 784 | + for cond in self.conditions: |
| 785 | + cons_list.append(str(cond)) |
| 786 | + ret_str += f" conditions={(cons_list)}]" |
| 787 | + return ret_str |
| 788 | + |
| 789 | + def get_struct(self, simplified: bool = False) -> ReprStruct: |
| 790 | + """Return the AST structure of the object.""" |
| 791 | + value: ReprStruct = { |
| 792 | + "key": self.key.get_struct(simplified), |
| 793 | + "value": self.value.get_struct(simplified), |
| 794 | + "target": self.value.get_struct(simplified), |
| 795 | + "iterable": self.iterable.get_struct(simplified), |
| 796 | + "conditions": cast( |
| 797 | + ReprStruct, |
| 798 | + { |
| 799 | + str(cond): cond.get_struct(simplified) |
| 800 | + for cond in self.conditions |
| 801 | + }, |
| 802 | + ), |
| 803 | + } |
| 804 | + |
| 805 | + key = ( |
| 806 | + f"DICT-COMPREHENSION#{id(self)}" |
| 807 | + if simplified |
| 808 | + else "DICT-COMPREHENSION" |
| 809 | + ) |
| 810 | + return self._prepare_struct(key, value, simplified) |
0 commit comments