OpenMaya: Pythonic iterators?

I discovered in the Maya API documentation that the iterators - for example the MItSelectionList - can be initialized in a Python fashion using the iter() function, and that you can then move the iterator using iternext(). But how does this work precisely? I’m doing an x-in-list, printing x and all I get is a reference to the iterator itself!

from maya.api import OpenMaya as om

_ = om.MSelectionList()

sel_itr = om.MItSelectionList(_).iter()
for x in sel_itr:

# <OpenMaya.MItSelectionList object at 0x0000023310727468>
# <OpenMaya.MItSelectionList object at 0x0000023310727468>
# <OpenMaya.MItSelectionList object at 0x0000023310727468>
1 Like

Well that is handy. Would have been nice if it actually implemented the __iter__ protocol directly, but so much better than nothing.

Except that it doesn’t work.
x is always a reference to the iterator and not the object in the MItSelectionList :frowning:

I’ve only got 2018 installed and it doesn’t seem to have an iter method on the MSelectionList nor can I for-loop over an MItSelectionList. So I’m just guessing here, but what you probably want to do is:

for x in sel_iter:

But if I had to guess, .iter is probably doing something like:

def make_iter(sel_list):
    sel_iter = om.MItSelectionList(sel_iter)
    while not sel_iter.isDone():
        yield sel_iter

Precisely - the topmost code is what I assumed Autodesk meant in their documentation.
Either the docs are incomplete or this code is incomplete coz right now I can’t see how we can use these functions in a practical way.

I mean it at least reduces the boilerplate of having to convert the MSelectionList to an MItSelectionList, and reduces the the need for the janky while loop.

I think the reason it doesn’t just loop over the objects is because you can either extract them with MitSelectionList.getDagPath() or MItSelectionList.getComponent() or both!

And in the face of ambiguity I’m glad they don’t guess.