Python Sugar

A really handy list comprehension technique that I am using heavily these days:

Instead of doing this:

for g in grGrps:
    gMeshes = self.meshesInGroup(g)
        if gMeshes:
            for m in gMeshes:
            # Append any meshes with lod0

Do this:

for g in grGrps:
    for msh in [msh for msh in self.meshesInGroup(g) if self.meshesInGroup(g)]:
        # Append any meshes with lod0

In the above case we are checking if the method returns anything, but the if portion is completely unrelated to the loop so it can be any if arg and/or/not appended to it. You could actually ADD ‘and‘_lod0’, to the if statement. Sometimes you may not want to go too crazy with the line length to keep things readable…

Another handy use is to filter file extensions when using os.walk:

for unused, unused, files in os.walk(os.path.abspath('yourPath')):
    for xml in [filename for filename in files if fnmatch(filename, '*.xml')]:
        #do something

In the last usage example, we are iterating through a list of attribute objects (pymel) and want to exclude attributes in an exclude list:

for sh in self.hlslShaders:
    for att in [att for att in sh.listAttr() if not in excludes]:
        # Do Stuff

Having made the full MEL to Python transition at this point I am a much happier tools writer and I could never imagine going back. Whenever I have to revisit old MEL code, it is sort of painful. This particular syntax may be a given to a seasoned Python coder, but I just picked it up and find it incredibly useful.

Hoping to pass it along to anyone out there that is in a similar situation.


2 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *