Wednesday, August 25, 2010

Monday, August 23, 2010

Python Cheat Sheet

This is for everyone who, for whatever reason, are putting off learning Python.  Ideally, if you are coming from another language such as MEL or Perl, you should be able to skim through these demos and have no problem transitioning to Pythonic syntax.  The following Python snippets are selections from the online documentation at http://docs.python.org/, which I modified whenever possible to fit into a Maya context.

Data Structures
  • Strings
    myString="Hello"
    mySecondString="World"
    result=myString+mySecondString
    myMultilineString="""Hello World.
    What a beautiful world it is."""
    myRawString=r"C:/Users"
      
    firstLetter=myString[1]
    lastLetter=myString[-1]
    firstWord=myString[0:4] 
    • Unicode: Since Maya is used internationally, multiple language packs are supported which require a unicode character set. Think of unicode as the big brother of the standard ASCII model. You will not see anything unusual as the result of MEL commands, however Maya will return Python commands in unicode notation. As long as your in Maya the prefix u can be ignored, however, if you are writing output to a file they will have to be converted to ASCII.
    print cmds.ls(cameras=1)
    >>[u'frontShape', u'perspShape', u'sideShape', u'topShape']
    
    • Lists
    print cmds.ls(cameras=1)
    >>[u'frontShape', u'perspShape', u'sideShape', u'topShape']
    
    myToys=["yoyo", "cup", "ball", "crayon"] #the names of your objects
    cmds.select(myToys)
    
    firstToy=myToys[1]  #yoyo
    numToys=len(myToys)  #3
    
      • List Comprehensions: These are used to create lists from any iterable object.  The first time I used them was to retrieve the nth column in a matrix stored as vectors.
    myMatrix=[[1,2,3,4],[1,2,3,4],[1,2,3,4]]
    thirdRow=myMatrix[2] #[1,2,3]
    thirdColumn=[x[2] for x in myMatrix] #[3,3,3]
    
    • Tuples: Are similar to list except they cannot be modified, also known as immutable.
    myList=["Hello", 1]
    myList[1]=5 #can change the value
    
    myTuple=("Hello", 1) 
    myTuple[1]=5 #ERROR
    
    • Sets: Sets are GREAT.  They are just like lists but prevent duplicate elements.
    keyLight= cmds.lightlink(light="keyLight", query=1) #return all objects set to receive light from keyLight
    backLight= cmds.lightlink(light="backLight", query=1) #return all objects set to receive light from backLight
    
    lightsList=keyLight+backLight #12 items, lists duplicates
    lightsSet=set(keyLight+backLight) #8 items, returns only unique elements
    
    • Dictionaries: Sometimes referred to as hashes or associative arrays, are used to store data in name, value pairs.
    myCameras=cmds.ls(cameras=1)
    myTextures=cmds.ls(textures=1)
    myScene={'cameras':myCameras, 'textures':myTextures} #myScene stores all the cameras and textures in the scene
    
    print myScene.keys()
    print myScene.values()
    print myScene["cameras"]
    
    Control Flow
    • While Loops: Use extreme caution when using while loops. There is no way to close Maya if you get caught in an infinite loop.
    while x<10:
        print x
        x+=1 #make sure to terminate the loop!
    
    • If Statement
    if (myValue==10 or myValue==20) and myValue!=30
        print myValue
    elif myValue==0:
        print "Cannot be 0"
    else: #all occurances
        pass #pass keeps Pythonic syntax, useful as placeholders 
    
    • For Statement
    for x in range(10):
        print x, someList[x]
    
    for index, eachItem in enumerate(iterableItem):
        print index, eachItem
    
    • Exceptions
    sphereAttrs=cmds.listAttr('pSphere1')
    for eachAttr in sphereAttrs:
        print eachAttr+":",
        try:
            print cmds.getAttr("pSphere1."+eachAttr)
        except:
            print "Cannot Read"
    
    Functions
    def myFunction(arg=None): #defines function myFunction that accepts an argument arg that defaults to None
        print arg
        return 1
    myFunction("Hello World") #calls myFunction
    
    Classes
    class newClass():
        myInt=5 #class variables
        @classmethod  #class method decorator
        def getInt(cls): #class method
            return cls.myInt
        def __init__(self, arg): #gets automatically called when an object is instantiated
            self.myString=arg  #self are instance variables, they are unique per object
        def myFunction(self, arg):
            print arg, self.myString
    
    myClass =newClass("Hello") #creates a new object from class newClass, objects are instances of a class
    myClass.myFunction("World") #Hello World
    print myClass.myFunction.myString #Hello
    print newClass.myInt #5
    print newClass.getInt() #5
    I hope this will get you all started in the right direction. The vast majority of all your scripts will come from topics discussed here, everything else beyond this cheat sheet will merit a dedicated post. If you have further questions I find it's easiest to just to Google the topic. Even though I am a member of http://www.python-forum.org/pythonforum/ I rarely, if ever have to create a new thread. On the other hand I highly recommend the Maya Programming Forum on http://forums.cgsociety.org/ since Maya specifics sometimes get hazy. Hopefully you are all already members.