Pros and cons of different ways to get selected objects?

I am a novice when it comes to coding. I’ve been reading a lot of the help threads on this forum and on stack exchange and the Blender discord and from the various answers I’ve seen at least 3 different ways to get a list of the currently selected objects. I was wondering why one would want to check view_layer.objects or context.scene.objects when context.selected_objects exists and seems like it would be the most performant (least amount of iterating over the scene).

foo = context.selected_objects
bar = []
for o in bpy.context.view_layer.objects.selected: 
    bar.append(o)
baz = [o for o in context.scene.objects if o.select_get()]

I’m not sure what method is the fastest, the difference in speed is negligible
you can benchmark them yourself
https://docs.blender.org/api/current/info_best_practice.html#time-your-code

But output of these methods can be different

If you select some object, enter local mode (/ on numpad) and select more objects in outliner or with python
Then running context.selected_objects in operator in 3D Viewport will not return all selected objects, but only those selected objects which are in 3D Viewport local mode

but
context.view_layer.objects.selected[:]
and
[o for o in context.scene.objects if o.select_get()]
return all selected objects, even those not in local mode

1 Like