Ways to reduce ls selection command in overall code

Hi all, sorry for this noob question but I came to realize that in some of the codings that I have did, I am exceeding the use of the ls command.

In this current code of mine, I have been using cmds.ls(sl=True) in almost all of my 6 functions out of the 9 functions that I writtin in my class function.
Was wondering if there are any better ways that I can reduce the need to do so?

I tried making it “global” by defining it right before my class, but there are some consequences in which if I did not select anything before the code is executed, it is deeming my selection is empty.

selection = cmds.ls(sl=True)

class mainWindow(QDialog):
    ...
    ...

So how is this a problem? If you need it to work on the selection at the time of the method being run you should put it in the method.

you could store the active selection when the UI is opened as a class attribute, and retrieve it when a method runs. However, you won’t be guaranteed to be up to date with the user at the time they press a button.

It’s hard to know what solution to propose not knowing your code structure or its functionality, however you could use a keyword arg that specifies the objects to operate on. If it is not given, get the current selection.

def foo(objects=None):
    if objects is None:
        objects = cmds.ls(sl=True)

also remember that Maya’s default behavior is to operate on the selection if no arguments are provided. So these two scripts are equivalent:


for item in cmds.ls(sl=True):
     cmds.xform(item, t=(1, 0 , 0),  r=True)

# is the same as

cmds.xform(t=(1, 0 , 0),  r=True)

# if you have things selected 

Hey, thanks guys. I agreed with capper that it is pretty hard to propose without knowing the code structure. Nevertheless, the code that I am currently working on requires the User to select on an object every now and then. Just thought that there are some sort of ways to reduce the need of the selection command.

The feedback I received here are wonderful :slight_smile:

Ya can’t do much without seeing the structure of the code. But also I just wouldn’t worry about it unless things aren’t running fast enough and you need to optimize.

Assuming that these functions are run at different times (like they are triggered discretely by buttons and not all run in sequence through a main function), I recommend using the current selection each time they are run. Either that or make sure that it is made obvious to the user that their selection at the start will be used across all buttons/functions. It may be confusing if the user expects their current selection at all times to be what is operated on when instead you are using a selection state that was stored at some other point in time.

Thanks again, guys. Will take the advices into account and work my way around as I do the coding :smiley: