om2-BeginnersGuide 01 - Managing Selections
Disclaimer:
All code here is provided as is without support.
Use at your own risk! These posts assume you have some knowledge of import/running python script in maya. If Gifs/Images are not displaying in Chrome try a different browser.

If you’re keen read this now: Selecting_with_the_API 2018

So I’ve selected all the default camera’s in scene and want to access the list of selected items in scene.

cmds:

    from maya import cmds
    currentSelection = cmds.ls(sl=True)
    # Result: [u'persp', u'top', u'front', u'side']

om2:

    from maya.api import OpenMaya as om2
    currentSelection = om2.MGlobal.getActiveSelectionList()
    # Result: <OpenMaya.MSelectionList object at 0x0000018AA59E5EB0> #
    
    # or you can create your OWN MSelectionList and add to it
    currentSelection = cmds.ls(sl=True, l=True)
    mSel = om2.MSelectionList()
    for eachNode in currentSelection:
        mSel.add(eachNode)

So the most noticeable difference here is;

And since cmds returns a python list of strings you can very quickly use:

    for myName in currentSelection:
        print(myName)

But what the heck do you do with an MSelectionList()?
We can’t do this on the MSelection list?! Well we have to use the MSelectionList.length() arg and iter using the .getDependNode() method. eg:

    currentSelection = om2.MGlobal.getActiveSelectionList()
    for x in range(currentSelection.length()):
        myMObject = currentSelection.getDependNode(x) #-> MObject
        myMFn = om2.MFnDependencyNode(myMObject) # -> MFnDependencyNode function set
        print("{} is currently selected".format(myMFn.name()))

    >>persp is currently selected
    >>top is currently selected
    >>front is currently selected
    >>side is currently selected
    
    # Note you can also use getSelectionStrings on the MSelection list to get a tuple of
    # string names (though "but for non-contiguous components there will be a
    # separate string for each distinct block of contiguous elements"):
    currentSelection.getSelectionStrings()
    >> # Result: (u'persp', u'top', u'front', u'side') #

Since you’ve most likely just come from the reading the API post lets look at the docs for the getDependNode(x) method.

APIom2

You can clearly see it says `Returns: MObject’ so you now know what is being returned by this method!

In the example above I used it to create an instance of the MFnDependencyNode and print the name.

And this is now most likely starting to shine a light on the crux of the differences for you between cmds and om2.

om2 is a little lower level. You’re dealing more with python classes / function sets now, and you’re having to handle your MObjects, MPlugs etc so you have to keep track of your types and what accepts/returns what.

If you didn’t already; read: Selecting_with_the_API 2018

.. onwards… Handling Nodes & Attributes