[Python-ideas] Trailing-based state restoration
SAVEANT Pierre
pierre.saveant at thalesgroup.com
Thu Dec 17 12:12:40 EST 2015
Hi,
I got a proposal for a new feature in Python in order to perform hypothetical reasoning in a very simple way.
Hypothetical reasoning is mainly used in problem solving search algorithms.
In such a process, variables are temporally assigned and later restored to their preceding value.
With the assumption that only a small fraction of the variables changes at the same time, it is more efficient to store undo information instead of copying the entire state.
The basic data structure to handle these moves efficiently is called a trail which is mainly a stack with markers.
Potentially this mechanism can be provided to any object type of Python.
Only few lines are needed to implement the mechanism using the reflexive power of Python.
A deeper implementation could hide the process in the internal data representation in order to offer this new feature in a seamless way.
This new feature is activated with the specification of thee primitives:
- push()
- back()
- assign(object, attribute, value)
push : declare a new hypothetical state.
back : restore the previous state.
assign(object, attribute, value) : assign the value to the attribute of the object in the current state.
In addition a primitive can be provided to go back to a specific state:
backtrack(n): restore the state number n.
EXAMPLES
class Var:
def __init__(self, value):
self.value = value
def __str__(self): return"{}".format(self.value)
def test1():
V1 = Var(10)
assert V1.value == 10
push()
assign(V1, 'value', 100)
assert V1.value == 100
back()
assert V1.value == 10
def test2():
V1 = Var(0)
for i in range(8):
push()
for j in range(5):
assign(V1, 'value',(j+1)+i*5-1)
assert V1.value == 39
assert current() == 8
backtrack(6)
assert V1.value == 29
assert current() == 6
backtrack(4)
assert V1.value == 19
assert current() == 4
backtrack(0)
assert V1.value == 0
assert current() == 0
The assign procedure is used in place of the standard assignment denoted by the "=" operator.
In a seamless integration the "=" assignment operator could be overridden when the variable has been previously declared as "recordable" (require a declaration primitive or a type declaration).
Is anybody interested by this new feature?
Pierre Savéant
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151217/1b60479f/attachment.html>
More information about the Python-ideas
mailing list