Using GetSelectedObjects

This is a dumb basic Python question I have after not doing any scripting for months, but I’ve got a script using doc.Objects.GetSelectedObjects and I somehow just realized that having nothing selected doesn’t return a null value as I assumed, it returns an empty enumeration, and there seems to be no quick easy way to just check if it’s empty?

I tried stepping through it and setting a flag if there is anything in it, and that works to check that it’s empty but if it’s not the script subsequently fails to do anything with the selected objects, like trying to look into this has changed it?!? Am I losing my mind here?

Hi Jim,

Does this work for you?

import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino

test=sc.doc.Objects.GetSelectedObjects(False,False)
objs=list(test)
if objs:
    obj_ids=[obj.Id for obj in objs]
else:
    print("No objects selected")

Or this - @Helvetosaur was a bit faster

sel = Rhino.RhinoDoc.ActiveDoc.Objects.GetSelectedObjects(False, False)

selected = False
for item in sel:
    print("aha")
    selected = True

print(selected)

there seems to be no quick easy way to just check if it’s empty?

Calling bool on it should work whether it’s None or an empty container (e.g. []). if statements call bool on their condition automatically.

That’s lovely and elegant, but it will error if sel is None.

1 Like

Thanks for the attempts guys, they’re all working to figure out if there is something but they’re all…wrecking the list somehow? The script does nothing at all if I do this check.

    selected=sc.doc.Objects.GetSelectedObjects(False,False)
 
   objs=list(selected)
    if objs:
        print "there is something"
    else:
        print "nothing selected"
   
    rhino_objects=selected
...carry on with stuff with rhino_objects

So that works fine for telling me it’s empty but far as the subsequent code doing stuff with “rhino_objects” goes, it does nothing. If I get rid of the checking stuff it works…which I mean, the code works fine without error but I want to check now and tell the user that nothing is selected if nothing is selected.

Dunno, this seems to work here to change the color of selected objects to red…

import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino,System

selected=sc.doc.Objects.GetSelectedObjects(False,False)
rhobjs=list(selected)
if not rhobjs:
    print("No objects selected")
else:
    for rhobj in rhobjs:
        rhobj.Attributes.ColorSource=Rhino.DocObjects.ObjectColorSource.ColorFromObject
        rhobj.Attributes.ObjectColor=System.Drawing.Color.FromArgb(255,255,0,0)
        rhobj.CommitChanges()
sc.doc.Views.Redraw()

Yeah I don’t understand why I got it working, but I did…