Skip to content

Commit

Permalink
fix(3.13): handle changed positions for __exit__ of ast.With
Browse files Browse the repository at this point in the history
  • Loading branch information
15r10nk committed Sep 15, 2024
1 parent 4acebfa commit c27f236
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
52 changes: 52 additions & 0 deletions executing/_position_node_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,53 @@ def fix_result(
# https://github.com/python/cpython/issues/123142

return node.parent.parent

if sys.version_info >= (3, 12,6) and instruction.opname == "CALL":
before = self.instruction_before(instruction)
if (
before is not None
and before.opname == "LOAD_CONST"
and before.positions == instruction.positions
and isinstance(node.parent, ast.withitem)
and isinstance(node.parent.parent, (ast.With, ast.AsyncWith))
and any(item.context_expr == node for item in node.parent.parent.items)
):
# node positions for with-statements have change
# and is now equal to the expression which created the context-manager
# https://github.com/python/cpython/pull/120763

# with context_manager:
# ...

# but there is one problem to distinguish call-expressions from __exit__()

# with context_manager():
# ...

# the call for __exit__

# 20 1:5 1:22 LOAD_CONST(None)
# 22 1:5 1:22 LOAD_CONST(None)
# 24 1:5 1:22 LOAD_CONST(None)
# 26 1:5 1:22 CALL() # <-- same source range as context_manager()

# but we can use the fact that the previous load for None
# has the same source range as the call, wich can not happen for normal calls

# we return the same ast.With statement at the and to preserve backward compatibility

return node.parent.parent

if (
sys.version_info >= (3, 12,6)
and instruction.opname == "BEFORE_WITH"
and isinstance(node.parent, ast.withitem)
and isinstance(node.parent.parent, (ast.With, ast.AsyncWith))
and any(item.context_expr == node for item in node.parent.parent.items)
):
# handle positions changes for __enter__
return node.parent.parent

return node

def known_issues(self, node: EnhancedAST, instruction: dis.Instruction) -> None:
Expand Down Expand Up @@ -895,6 +942,11 @@ def node_match(node_type: Union[Type, Tuple[Type, ...]], **kwargs: Any) -> bool:
def instruction(self, index: int) -> Optional[dis.Instruction]:
return self.bc_dict.get(index,None)

def instruction_before(
self, instruction: dis.Instruction
) -> Optional[dis.Instruction]:
return self.bc_dict.get(instruction.offset - 2, None)

def opname(self, index: int) -> str:
i=self.instruction(index)
if i is None:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
async def wait():
async with something:
pass

0 comments on commit c27f236

Please sign in to comment.