I need 4 instances of a property group sub-class in my primary class, and I want to access them (main.sub[*].x) based on an enum or index.

Here's a fictitious (and boring) example to help illustrate what I'm trying to achieve:

MyTypes = ['A','B','C','D']

class TypeClass(bpy.types.PropertyGroup):
    ... unrelated things in here ....

class MainClass(bpy.types.PropertyGroup):
    States : PropertyGroupList(type=TypeClass,enum=MyTypes)

MainObject.States['A'].x = 2

Since there doesn't seem to be a built-in mechanism to construct properties, I'm not sure how I could achieve this with a CollectionProperty, unless I defined my own handler to generate the 4 elements. I have zero experience in dealing with python lists or arrays, other than defining empty lists and iterating/adding/removing. Any advice is appreciated.

Edit: (more than once)

This is the best way I've found to do this so far, and it has little to do with lists:

from enum import Enum

class ThingTypes(Enum):
    A = 0
    B = 1
    C = 2
    D = 3

class MainClass(bpy.types.PropertyGroup):

    # data for each mode
    ModeA : PointerProperty(type = TypeClass)
    ModeB : PointerProperty(type = TypeClass)
    ModeC : PointerProperty(type = TypeClass)
    ModeD : PointerProperty(type = TypeClass)

    # access mode based on enum index
    def Mode(self,type_index):
        if type_index == ThingTypes.A:
            return self.ModeA
        elif type_index == ThingTypes.B:
            return self.ModeB
        elif type_index == ThingTypes.C:
            return self.ModeC
        elif type_index == ThingTypes.D:
            return self.ModeD
            raise Exception("Invalid mode")

... usage ...

MainObject.Mode(ThingTypes.C).Attribute = 0

If there is a better way, I'm interested to find it. Preferably some way to actually define the sub-class instances as a list, then just access the list using the enum/index. Thanks for any info.

  • $\begingroup$ In my project, I've switched most of the data in the add-on to use lists, and access those with a type index, which is great because I've divided most of my code by 4. But I still haven't found any way to do this inside of a class derived from PropertyGroup. When I try to define anything as a list inside of the class, something breaks down in the Blender pipeline. I'm still relying on the if-else grab function at the moment. My guess is there is no other way to pull this off. $\endgroup$ – Robert Sep 16 at 12:22

Your Answer

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

Browse other questions tagged or ask your own question.