Force attribute value on potentially non-existent or locked PyNode 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.deleteAttr(name)

    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.