If statement for Custom Property not working inside UI Panel

I’m making a UI panel that will show the value of an objects custom property (called “PreviewIndex”) and it works for items that have the custom property:
23_09-59-28_blender-304
But not for objects that dont:
23_09-59-41_blender-305
I assumed it would just check is the variable existed and then continue but it throws an error and doesnt draw the rest of the panel:

KeyError: 'bpy_struct[key]: key "PreviewIndex" not found'
location: <unknown location>: -1

What am I missing and how should I make the if statement check if the variable exists and if not just continue?
Here is the panel code:

def draw(self, context):
        layout = self.layout
        scene = context.scene
        mytool = scene.my_tool

        row = layout.row(align=True)
        op = row.operator("object.materialpreview", text="Init")
        op.MP_Action = ("Initialize")
        if context.object.data["PreviewIndex"]:         #This line ------------
            row.prop(context.object.data, '["PreviewIndex"]')
        op = row.operator("object.materialpreview", icon="TRIA_UP", text="")
        op.MP_Action = ("Increase")
        op = row.operator("object.materialpreview", icon="TRIA_DOWN", text="")
        op.MP_Action = ("Decrease")
if 'PreviewIndex' in context.object.data:
    print('do stuff')

since custom properties can also be accessed as attributes, here’s what you do in that situation:

if hasattr(context.object.data, "PreviewIndex"):
    print('do stuff')
5 Likes

That worked, thanks for taking the time! :smiley:

your 1st answer @testure is not intuitive but works like a charm !

Thanks a lot ! :smiley:

Happy blending !

well if it’s not intuitive you can blame the Python foundation, that’s just how things are done with this language :slight_smile:

1 Like