3
$\begingroup$

What is the best practice way to store a python list defined in an addon as a scene variable in Blender?

Using

global mylist

doesn't work because the variable is not a Blender-specific type and therefore not saved after a button click operation completes. I would like the list to exist in the Blender environment so that I can access it from future function calls.

My current solution is to use Blender Collection Properties, with my own wrapper functions, but this seems kind of excessive:

bpy.types.Object.CP_list = bpy.props.CollectionProperty(type=bpy.types.PropertyGroup)

def CollectionProperty2list(CP, numerical = False):
    new_list = []
    if (numerical):
        for elt in CP:
            new_list.append(float(elt.name))
    else:
        for elt in CP:
            new_list.append(elt.name)
    return (new_list)

def list2CollectionProperty(mylist, CP):
    CP.clear()
    for elt in mylist:
        CP.add().name = str(elt)  # stores string for numerical or string input
    return()

storing:

list2CollectionProperty(py_list, obj.CP_list)

retreiving:

py_list = CollectionProperty2list(obj.CP_list)
$\endgroup$
  • $\begingroup$ What seems more practical to me would be a way to store an entire python list to a single Blender variable, rather than assigning each element separately, and then retrieving each element separately. $\endgroup$ – Animik Aug 11 '17 at 16:48
4
$\begingroup$

Storing a list as an ID property

# assign a list
>>> C.scene["mylist"] = [1, 1, 1, 1, 1, 1]
>>> C.scene['mylist']
<bpy id property array [6]>
# save file, reopen
>>> C.scene['mylist'].to_list()
[1, 1, 1, 1, 1, 1]

This will work for lists where all items are of the same type: strings, ints, floats or booleans (booleans as ints).

Could try using your methods above as getters / setters ... but I don't think get is available for bpy.props.CollectionProperty.

$\endgroup$
  • $\begingroup$ So simple! Also works for objects, without having to use the Blender properties: ob["mylist"] = py_list $\endgroup$ – Animik Aug 18 '17 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.