Skip to content

[mypyc] Fix with statements when the body reassigns the context manager - #22561

Open
Jahongir-Qurbonov wants to merge 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-with-rebind-target
Open

Jahongir-Qurbonov wants to merge 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-with-rebind-target

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

If a with statement's context manager was a local variable and the body assigned to that variable, __exit__ was called on the new value instead of the original context manager, since the variable's register was read again after the body:

x = Native("a")
with x:
    x = Native("b")  # "b".__exit__() was called; "a" was never exited

This affected native and non-native context managers, async with and generators. With librt.threading.Lock, the new lock was released, so with lock: lock = Lock() raised RuntimeError: cannot release an unlocked lock and left the original lock acquired. Assignments through a with target (with x as x: or with x, y as x:) or a walrus had the same issue, and del x in the body caused an UnboundLocalError on exit.

Now, if the with statement may assign to the local variable that holds the context manager, its value is copied to a new register first. This reuses the assignment collector that #22137 added for for loops.

If the context manager was a local variable that the with statement
assigned to (in the body, through a target or with a walrus), __exit__
was called on the new value of the variable instead of the original
context manager. Copy the context manager to a new register in this
case, using the same assignment collector as for loops.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant