Hello all.
I am trying to embed jython in a Java app, but I have encountered a
stumbling block.
I want to instantiate and initialize a PythonInterpreter object, immediately
save the initialized state of the interpreter object, and periodically
restore that initialized state. The PythonInterpreter getLocals() and
setLocals() methods seem to be just what I need:
myInterpreter = new PythonInterpreter();
// Set up the initial state of myInterpreter.
myInterpreter.exec("from java.lang import Integer");
... much more setup code here ...
// Save the initial state of myInterpreter.
PyObject initialState = myInterpreter.getLocals();
// Change the state of myInterpreter.
myInterpreter.exec("from java.util import Random");
... much more code here ...
// Try to restore the initial state of myInterpreter.
// This doesn't work, since 'initialState' was modified
// by the previous invocation of exec().
myInterpreter.setLocals(initialState);
Unfortunately, this code does not work. The getLocals() method returns a
*reference* to the PythonInterpreter.locals object, rather than a deep copy.
The result is that the object referenced by 'initialState' is modified when
I make additional calls to PythonInterpreter.exec().
Peeking at the source code for PythonInterpreter allowed me to create the
following hack:
... Set up the initial state of myInterpreter, as before ...
// Save the initial state of myInterpreter.
PyStringMap localsMap = (PyStringMap)
myInterpreter.getLocals();
PyObject initialState = (PyObject) localsMap.copy();
... Change the state of myInterpreter, as before ...
// Restore the initial state of myInterpreter.
myInterpreter.setLocals(((PyStringMap)
initialState).copy());
Of course, this code will break if the return type of getLocals() ever
changes.
How can I achieve the same result without resorting to a hack? Should
getLocals() return a deep copy of PythonInterpreter.locals? Am I using the
getLocals() and setLocals() inappropriately?
Thanks.
Regards,
-- William Byrd
|