0
$\begingroup$

I want to check whether a certain shapekey exists at the active mesh. How can I do that?

(Background: I have written a script, which dumps all shapekeys of a mesh with the associated values into a a textfile. Another scripts reads this files and assigns the values back to another mesh of a newer version. If the set of defined shapekeys changes, the latter scripts fails with "shapekey not found". I want to check for this case beforehand)

$\endgroup$
2
  • $\begingroup$ You mean check for a shapekey with a certain name? $\endgroup$
    – scurest
    Commented Jan 12, 2021 at 5:23
  • $\begingroup$ yes...exactly :) $\endgroup$
    – mcc
    Commented Jan 12, 2021 at 5:59

2 Answers 2

4
$\begingroup$

Using get

Another way than testing if the name is in the collection keys, is to use get. If an object has shapekeys then

sk = ob.shape_keys.key_blocks.get("Foo")

will return the shapekey named "Foo" if it exists, else None.

Similarly to a poll method, can make a helper method and pass it the object and the shapekey name.

def has_shape_key(ob, name):
    return bool(
        hasattr(ob.data, "shape_keys")
        and ob.data.shape_keys
        and ob.data.shape_keys.key_blocks.get(name)
        )

Can string ands together in a python expression the first one to "fail" ie is False will abort further evaluating the expression and return False.

$\endgroup$
1
  • $\begingroup$ Thank you for the solution this and the other one are both valid for me. $\endgroup$
    – mcc
    Commented Jan 13, 2021 at 7:45
3
$\begingroup$

You can test whether a collection has an item named 'foo' with 'foo' in collection. So

def active_object_has_keyblock(name):
    ob = bpy.context.active_object
    if not ob or ob.type != 'MESH':
        return False

    mesh = ob.data
    if not mesh.shape_keys:
        return False

    return name in mesh.shape_keys.key_blocks
$\endgroup$
1
  • $\begingroup$ Thank you for the solution this and the other one are both valid for me. $\endgroup$
    – mcc
    Commented Jan 13, 2021 at 7:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .