Monday, February 11, 2013

Python - Keeping things brief AND readable

I've always believed that clarity should trump brevity when it comes to scripting.  This is especially true of Python, since it's already so readable.  That's why some things I've written area little longer than they really need to be.  However, if I stumble across a way to keep things brief and readable, I try to use it as often as possible.

For instance, in Maya with Python this is how you check for a window and delete it if it exists:

if mc.window(winName, exists = True):
        mc.deleteUI(winName)

But you could do the same thing with less typing:

try: mc.deleteUI(winName)
except: pass

I also like to check the version of Maya that the user is using to avoid conflicts and such.  I like dockable UI's but versions of Maya older than 2011 can't support them.  So if the user has Maya 2011+, the will dock, otherwise it will float.  I've been doing it like this:


class ExampleClass():
  def __init__(self):
 
  self.dock = ""
 
         #Get the users version of Maya
  self.v = mm.eval("getApplicationVersionAsFloat")

  if self.v >= 2011:
  self.dock == True
  else:
  self.dock == False

But you can do the same thing with FAR less lines:


class ExampleClass():
  def __init__(self):

  #Get the users version of Maya
  self.v = mm.eval("getApplicationVersionAsFloat")
  self.dock = True if self.v >= 2011 else False

And it's just as readable.
EDIT:

When I deleted my dockControl, sometimes my window wouldn't delete.  By using a try, escape and else clause you can ensure that everything will be deleted if it exists in your scene.


import maya.cmds as mc
import maya.mel as mm

class ExampleClass():
  def __init__(self):
  self.winName = "exampleWin"
  self.v = mm.eval("getApplicationVersionAsFloat")
  self.dock = True if self.v >= 2011 else False

  self.exampleUI(self.winName, self.dock)

  def exampleUI(self, winName, dockOption):
  try: mc.deleteUI(winName + "_dock")
  except: mc.deleteUI(winName)
  else: pass

  exWindow = mc.window(winName, widthHeight = [300, 300])
exLayout = mc.rowColumnLayout()

  if dockOption:
  dockWindow = mc.dockControl(winName + "_dock", area = "right", allowedArea = "right", content = exWindow)
  else:
  mc.showWindow(winName)



~Melissa


No comments:

Post a Comment