|
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 |
|
@@ -792,3 +795,66 @@ def get_struct(self, simplified: bool = False) -> ReprStruct:
|
792 | 795 | else ASTNodes().get_struct(simplified),
|
793 | 796 | }
|
794 | 797 | return self._prepare_struct(key, value, simplified)
|
| 798 | + |
| 799 | + |
| 800 | +@public |
| 801 | +@typechecked |
| 802 | +class DictComprehension(Comprehension): |
| 803 | + """AST node for dictionary comprehensions.""" |
| 804 | + |
| 805 | + key: Expr |
| 806 | + value: Expr |
| 807 | + |
| 808 | + def __init__( |
| 809 | + self, |
| 810 | + key: Expr, |
| 811 | + value: Expr, |
| 812 | + target: Expr, |
| 813 | + iterable: Expr, |
| 814 | + conditions: Optional[Iterable[Expr] | ASTNodes[Expr]] = None, |
| 815 | + is_async: bool = False, |
| 816 | + loc: SourceLocation = NO_SOURCE_LOCATION, |
| 817 | + parent: Optional[ASTNodes] = None, |
| 818 | + ) -> None: |
| 819 | + super().__init__( |
| 820 | + target=target, |
| 821 | + iterable=iterable, |
| 822 | + conditions=conditions, |
| 823 | + is_async=is_async, |
| 824 | + loc=loc, |
| 825 | + parent=parent, |
| 826 | + ) |
| 827 | + self.key = key |
| 828 | + self.value = value |
| 829 | + self.kind = ASTKind.DictComprehensionKind |
| 830 | + |
| 831 | + def __str__(self) -> str: |
| 832 | + """Return a string representation of the object.""" |
| 833 | + conditions_str = [] |
| 834 | + if hasattr(self, "conditions") and self.conditions: |
| 835 | + conditions_str = [str(cond) for cond in self.conditions] |
| 836 | + |
| 837 | + ret_str = ( |
| 838 | + f"DictComprehension[key={self.key}, value={self.value}," |
| 839 | + f" target={self.target}, iterable={self.iterable}, " |
| 840 | + f" conditions={conditions_str}," |
| 841 | + f" is_async={self.is_async}]" |
| 842 | + ) |
| 843 | + return ret_str |
| 844 | + |
| 845 | + def get_struct(self, simplified: bool = False) -> ReprStruct: |
| 846 | + """Return the AST structure of the object.""" |
| 847 | + value: DictDataTypesStruct = { |
| 848 | + "key": self.key.get_struct(simplified), |
| 849 | + "value": self.value.get_struct(simplified), |
| 850 | + "target": self.target.get_struct(simplified), |
| 851 | + "iterable": self.iterable.get_struct(simplified), |
| 852 | + } |
| 853 | + if hasattr(self, "conditions") and self.conditions: |
| 854 | + value["conditions"] = self.conditions.get_struct(simplified) |
| 855 | + key = ( |
| 856 | + f"DICT-COMPREHENSION#{id(self)}" |
| 857 | + if simplified |
| 858 | + else "DICT-COMPREHENSION" |
| 859 | + ) |
| 860 | + return self._prepare_struct(key, value, simplified) |
0 commit comments