Maya Python Error

Running Maya 2022.
in code below I would like to use
a variable with the setAttr() function
to move a locator to a different position.
Getting this error in the script editor:
line 2: Invalid argument 1, ‘[‘locator1’]’. Expected arguments of type ( list, )

import maya.cmds as cmds
Loc = cmds.spaceLocator( p=(0, 0, 0))
cmds.setAttr(Loc,’.translate’, 10,20,30)

Hello!
There are some issues with this code. Firstly, your cmds.spaceLocator function returns a list. To get the first item of the list you need to use something like this: list[list index], or in this case loc[0]. Then, if we’ll look at documentation , we’ll see that setAttr function takes an attribute (like ‘sphere1.translateX’) as first argument, but you are trying to pass your locator instead. Final code should look like this:

import maya.cmds as mc

loc = mc.spaceLocator(p=(0, 0, 0))
mc.setAttr(’{0}.translate’.format(loc[0]) , 10, 20, 30)

2 Likes

Ars is correct, I’ll just add another small thing…
you could solve this the same way he suggested, using the “format” method which is relatively new and is considered somewhat more pythonic:

loc = cmds.spaceLocator(p=(0, 0, 0))
cmds.setAttr(’{0}.translate’.format(loc[0]) , [10, 20, 30])

or you could do something like that in the second line:

cmds.setAttr(loc[0] + '.translate’ , [10, 20, 30])

which can sometimes look a little cleaner… same result, you can use whichever :slight_smile:

Hey, the above examples are great. Just to add some other options. In Maya 2022 it uses python 3 so you can make use of f strings for formatting strings. So you could write:

cmds.setAttr(f’{loc[0]}.translate’, [10, 20, 30])

Just in case anyone is interested you can do it cleaner in pymel:

import pymel.core as pm

loc = pm.spaceLocator(name=‘someName’)[0]
loc.translate.set(10, 20, 30)