Assign a Function to an Object Using Userdictionary

FYI,

My workaround in the past involved:

1 - Creating a dictionary where I store certain values for a given object using something like:

d= {}
d[guid] = {“parameter1”: “ABC”, “parameter2”:123, “function1”: “distance([0,0,0],[1,1,1])”}
d = str(d) # create a string representation of the dictionary, in this case if you print it our it would look like “{‘guid’: {‘function1’: ‘distance([0,0,0],[1,1,1])’, ‘parameter1’: ‘ABC’, ‘parameter2’: 123}}”

2 - Now I save my dictionary to the file using setDocumentData (or save it to the object using SetUserText):

rs.SetDocumentData(“MyData”, “d”, d) # save (i.e., serialize) the string representation of our dictionary to the file

3 - Whenever you want to read in the dictionary back again, you just do:

d = rs.GetDocumentData(“MyData”, “d”) # read in the string representation defining our dictionary. If you’ve used SetUserText, the you’ll have to call GetUserText

d = eval(d) # convert our string back to a dictionary

That’s it. Now if you have functions in your object, you just have use the eval again on each serialized function call. In this example you would do: eval(d[“function1”]).

Another workaround would be serialize your object using JSON (http://stackoverflow.com/questions/1458450/python-serializable-objects-json).

Cheers,
Bruno

1 Like