I am working in Maya using PyMEL (my goal is to leverage PyMEL to create more readable, object-oriented, Pythonic code than if I'd used maya.cmds). I need to set an attribute value on an arbitrary node. The attribute may not exist or, if it does exist, may be locked. I found that setAttr with force=True did not account for all these scenarios, so I made my own.

import pymel.core as core

def _maya_force_attribute(self, pynode, name, value, data_type="string", keyable=False, lock=False):

    if pynode.hasAttr(name):
        pynode.setAttr(name, lock=False)

    pynode.addAttr(name, dataType=data_type)
    pynode.setAttr(name, value, keyable=keyable, lock=lock)

What I discovered (I think) is that when using set/add/deleteAttr, you can't often use multiple flags at the same time.

Is there a command sequence or a command/flag combo that achieves the same result more directly?


From the documentation link you provided:

‘force’ kwarg, which causes the attribute to be added if it does not exist.

So the force kwargs does not seem to allow you to set a new dataType.

Hence it seems that the only way to set a new dataType is to remove and recreate the attribute. From this case, it seems hard to further simplify your code.

  • \$\begingroup\$ if, for the sake of argument, I could rely on the type being correct, would that change anything? \$\endgroup\$ – david.libremone Feb 22 '16 at 15:12
  • \$\begingroup\$ It depends on the lock behavior: can you do setAttr if the attribute is locked ? \$\endgroup\$ – oliverpool Feb 22 '16 at 16:21
  • 1
    \$\begingroup\$ nope (so I discovered) -- so it sounds like, based on my attempts and your feedback (and documentation highlighting :D ) there is no "built-in" way to do this -- thanks for the review! \$\endgroup\$ – david.libremone Feb 26 '16 at 13:02

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.