Return evaluated expression to the right of the dot of current attribute. Only evaluates builtin objects, and do any attribute lookup.
(
cursor_offset: int, line: str, namespace: dict[str, Any] | None = None
)
| 198 | |
| 199 | |
| 200 | def evaluate_current_expression( |
| 201 | cursor_offset: int, line: str, namespace: dict[str, Any] | None = None |
| 202 | ) -> Any: |
| 203 | """ |
| 204 | Return evaluated expression to the right of the dot of current attribute. |
| 205 | |
| 206 | Only evaluates builtin objects, and do any attribute lookup. |
| 207 | """ |
| 208 | # Builds asts from with increasing numbers of characters back from cursor. |
| 209 | # Find the biggest valid ast. |
| 210 | # Once our attribute access is found, return its .value subtree |
| 211 | |
| 212 | # in case attribute is blank, e.g. foo.| -> foo.xxx| |
| 213 | temp_line = line[:cursor_offset] + "xxx" + line[cursor_offset:] |
| 214 | temp_cursor = cursor_offset + 3 |
| 215 | temp_attribute = line_properties.current_expression_attribute( |
| 216 | temp_cursor, temp_line |
| 217 | ) |
| 218 | if temp_attribute is None: |
| 219 | raise EvaluationError("No current attribute") |
| 220 | attr_before_cursor = temp_line[temp_attribute.start : temp_cursor] |
| 221 | |
| 222 | def parse_trees(cursor_offset, line): |
| 223 | for i in range(cursor_offset - 1, -1, -1): |
| 224 | try: |
| 225 | tree = ast.parse(line[i:cursor_offset]) |
| 226 | yield tree |
| 227 | except SyntaxError: |
| 228 | continue |
| 229 | |
| 230 | largest_ast = None |
| 231 | for tree in parse_trees(temp_cursor, temp_line): |
| 232 | attribute_access = find_attribute_with_name(tree, attr_before_cursor) |
| 233 | if attribute_access: |
| 234 | largest_ast = attribute_access.value |
| 235 | |
| 236 | if largest_ast is None: |
| 237 | raise EvaluationError( |
| 238 | "Corresponding ASTs to right of cursor are invalid" |
| 239 | ) |
| 240 | try: |
| 241 | return simple_eval(largest_ast, namespace) |
| 242 | except ValueError: |
| 243 | raise EvaluationError("Could not safely evaluate") |
| 244 | |
| 245 | |
| 246 | def evaluate_current_attribute(cursor_offset, line, namespace=None): |