DEV Community

Cover image for Automatically Revert Temporary Value Changes in a with Block
tsuruko
tsuruko

Posted on

Automatically Revert Temporary Value Changes in a with Block

The new rollback() API introduced in triggon v2.0.0 can automatically revert temporary changes to variables and attributes made in a with block.
It also supports local variables, so it's only available on CPython 3.13+.


Code Example

Here's a simple example.

In this example, the variable x is assigned 99 inside the block, but once the block exits, it's restored to its original value, 1.

from triggon import Triggon

x = 1

with Triggon.rollback():
    x = 99
    print(x)
    # 99

print(x)
# 1
Enter fullscreen mode Exit fullscreen mode

You can also pass the names of variables or attributes to rollback(), so only the specified targets will be restored.

class A:
    a = 10

x = 0

# x isn't included in the rollback target
with Triggon.rollback("A.a"):
    x = 99
    A.a = -10
    print(x)
    # 99
    print(A.a)
    # -10

print(x)
# 99
print(A.a)
# 10
Enter fullscreen mode Exit fullscreen mode

Variables defined inside the block aren't restored.


triggon recently had a major update with 8 new APIs.
You can check the details in the release notes.

triggon is basically a label-based library, but rollback() can be used easily without registering labels, variables, or attributes in advance.

It also includes other unique features such as deferred execution and flexible early-return handling, so feel free to check it out if you're interested.

Top comments (0)