A SetValue decorator

January 19th, 2011 by Patrick Boucher - Viewed 4428 times -




In a recent post on the Softimage mailing list people were wondering how to temporarily change user preferences. There are many cases where that might be fun to do, think command logging, undo stack or PPG pop ups.

So here is a quick revisit of my past post on decorators but this one is very generalized.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import functools
 
xsi = Application
 
def tempSetValues(newVals):
def closure(func):
@functools.wraps(func)
def inner(*args, **kwargs):
# Save current values and set new ones
oldVals = {}
for k, v in newVals.iteritems():
oldVals[k] = xsi.GetValue(k)
xsi.SetValue(k, v, "")
 
# Run the wrapped function
try:
return func(*args, **kwargs)
finally:
# Restore the old values
for k, v in oldVals.iteritems():
xsi.SetValue(k, v, "")
return inner
return closure
view raw SetValue.py This Gist brought to you by GitHub.

And some example usage…

1 2 3 4 5 6
@tempSetValues({'preferences.General.undo': 0, 'preferences.scripting.cmdlog': False})
def doStuff(obj):
# Do stuff
# The undo stack will be set to 0 and cmdlog to False before execution and
# restored no matter if the call succeeds or fails.
pass

This version of the decorator is fun (Yeah!… I said fun.) because you can change any value in Softimage temporarily, as long as the value can be changed via a Application.SetValue() call.

I think you get the Gist of it.

3 Responses to “A SetValue decorator”

  1. Xavier says:

    And as long as the whole process does not fail. Otherwise they might stick to their modified value.

  2. True. If you get an all out XSI crash, you’re screwed.

    One could imagine saving the old vals to a file on disk and deleting the file on successful completion of the original function.

    If you get an all out crash, a startup event could find the file and reset the values.

    But that’s for another article.

  3. [...] could use a Python decorator to do this. Like this:LikeBe the first to like this post. This entry was posted in Scripting by [...]

Leave a Reply