[Maya Python API 1.0] Looking for suggestions, critique on some code

I’m finally diving into using the API to speed up some scripts that are solely using maya.cmds.

Looking for some advice, feedback from those with more experience on how to speed things up.

In this example, I want a list of lists, where each element is a list of UV coordinates that make up a UV shell.


def getUVShells(shape, uvSet=None):
    
    uvSets = cmds.polyUVSet(shape, q=True, allUVSets=True)
    if not uvSet or uvSet not in uvSets:
        uvSet = cmds.polyUVSet(shape, q=True, cuv=True)[0]
    
    mDag = rsApi.nameToMDag(shape) # helper function not included in sample
    meshFn = om.MFnMesh(mDag)
    
    uvShellArray = om.MIntArray()
    # uvShellArray is a list of Shell Indices sorted by UV Id.
    # [0, 0, 0, 1, 1, 1, 0] translates to UVs  0, 1, 2, 6 belong to a shell, while 3, 4, 5 belong to another

    shells = om.MScriptUtil()
    shellsPtr = shells.asUintPtr()
    meshFn.getUvShellsIds(uvShellArray, shellsPtr, uvSet)

    uvShells = {}
    for i, shellId in enumerate(uvShellArray):
        comp = '{0}.map[{1}]'.format(shape, i)
        if uvShells.has_key(shellId):
            uvShells[shellId].append(comp)
        else:
            uvShells[shellId] = [comp]
    return uvShells.values()

My question is, is constructing a string and sorting into a dictionary an ok way to do this, or should I rely on some other API functions to go from the uvShellArray to IV IDs?

Thanks.

Portions of this code was found on MayaStation.

That’s how I’d do it. The API doesn’t have many convenience functions for turning return types into different data-groupings; that is left up to the calling script. Also in this case the API has no use for the “shape.map[#]” string, since it would operate solely on the actual IDs of uvs.

Also, membership tests on a dictionary test against it’s keys, so you can use:
if shellId in uvShells:
instead of
if uvShells.has_key(shellId):

Which will offer the minor speed increase of no function lookup. Though I’d actually forgo that logic and just use a defaultdict (which will be faster than membership tests or dict.setdefault):

from collections import defaultdict

uvShells = defaultdict(list)
for i, shellId in enumerate(uvShellArray):
    uvShells[shellId].append('{0}.map[{1}]'.format(shape, i))

Thanks for the tips!