.rename() – Rename an object in Maya using Python

Used to rename objects:

cmds.rename(oldName, newName)

Used in context:

# Load the maya commands library
from maya import cmds

# Create a new variable 'selection'
# Store in it the currently selected objects
selection = cmds.ls(selection=True)

# If the selection contains 0 lists
if len(selection) == 0:
    # Then get all objects in the outliner and assign to 'selection'
    # long=True : Gives us the full path to the object, so we can determine any parents.
    # dag=True : We will only get objects which are listed in the outliner, and none of the hidden objects inside of Maya.

    selection = cmds.ls(dag=True, long=True)

    # Sort the list now stored in 'selection'
    # Sort by length
    # In reverse, giving us the longest path first
    selection.sort(key=len, reverse=True)

    # For each object now in the 'selection' variable
    for obj in selection:
        # Split the path by "|" (pipe)
        # Store in a new variable 'shortName'
        shortName = obj.split("|")[-1]
        # Lets create a new variable to store the relatives
        # We want to list the relatives, we only want the children, and we want the full path
        # If there are no relative, return an empty list (or []), so that we always get a consistent object type output
        children = cmds.listRelatives(obj, children=True, fullPath=True) or []
        # If the length of the children is exactly 1 (remember this is in a for loop)
        if len(children) == 1:
          # Then put the object at position 0 in the chidren list into a new variable 'child'
            child = children[0]
          # Place the objecttype of the child variable in the variable 'objtype'
            objtype = cmds.objectType(child)
            # Otherwise if the length of children is NOT 1 (so basically 0)
            # Put the object type of the object in the objtype variable
            objType = cmds.objectType(obj)
        if objType == "mesh":
            suffix = "geo"
        elif objType == "joint":
            suffix = "jnt"
        elif objType == "camera":
            # If we dont want to rename camera's, then provide this feedback in the output
            print "Skipping camera"
            # Tell the for loop to continue on to the next item
            # and not perform any of the other logic in the for loop for this current item
        # If none of the above conditions are met, then perform the else: logic
            # If none of the above statements are true, then the suffix is group or 'grp'
            suffix = "grp"

        # Lets now create a string which contains the new amended object name, based on our code:
        newName = shortName + "_" + suffix
        # Confirm the names are being suffixed correctly in the output before making the final changes
        print newName
        # Lets now rename the object
        cmds.rename(obj, newName)