Introduction To Python Scripting For Maya Artists
Introduction To Python Scripting For Maya Artists
com
INTRODUCTION TO PYTHON
SCRIPTING
FOR MAYA ARTISTS
By Chad Vernon
Table of Contents
Introduction .................................................................................................................................................. 4
Additional Resources .................................................................................................................................... 4
Python in the Computer Graphics Industry .................................................................................................. 4
Some Programs that support Python: ...................................................................................................... 4
What is Python used for? .......................................................................................................................... 4
Introduction to Python ................................................................................................................................. 5
What is Python? ........................................................................................................................................ 5
The Python Interpreter ............................................................................................................................. 5
What is a Python Script? ........................................................................................................................... 5
The Interactive Prompt ............................................................................................................................. 5
Running Python Scripts From a Command Prompt .................................................................................. 7
Shebang Lines ....................................................................................................................................... 8
Running Scripts in Maya and within a Python Session ............................................................................. 9
Python Modules ...................................................................................................................................... 11
Data Types and Variables ............................................................................................................................ 11
Variables ................................................................................................................................................. 11
Numbers and Math ................................................................................................................................. 13
Strings ..................................................................................................................................................... 14
String Formatting ................................................................................................................................ 15
String Methods.................................................................................................................................... 17
Lists ......................................................................................................................................................... 18
Tuples ...................................................................................................................................................... 19
Dictionaries ............................................................................................................................................. 20
Booleans and Comparing Values ............................................................................................................ 20
1
www.chadvernon.com
2
www.chadvernon.com
3
www.chadvernon.com
Introduction
This workshop is geared towards students with little to no scripting/programming experience. By the
end of this workshop, you will have the knowledge to write and run Python scripts inside and outside of
Maya. You will not learn everything about Python from this workshop. This workshop includes all the
basic information you should know in order to be proficient in reading, writing, running, and modifying
Python scripts. The purpose of this workshop is not to make you expert Python scripters, but to give you
a solid foundation from which in further your Python studies.
Additional Resources
Learning Python, 3rd Edition by Mark Lutz
Dive Into Python: http://www.diveintopython.org/toc/index.html
The python_inside_maya Google email list:
http://groups.google.com/group/python_inside_maya
http://www.pythonchallenge.com/
4
www.chadvernon.com
Introduction to Python
What is Python?
Python is a general purpose scripting language used in many different industries. It is a relatively easy to
use and easy to learn language. Python is used in web services, hardware testing, game development,
animation production, interface development, database programming, and many other domains.
The Python Interpreter can be downloaded and installed for free from the Python website
(http://www.python.org/download/). Linux, Unix, and OSX platforms usually ship with a Python
Interpreter already installed. Linux users can also use yum or apt-get to install Python. OSX users can
use homebrew or macports to install Python. Windows users can either use Chocolatey to install Python
or download and install the interpreter if they want to use Python outside of programs that come with
an Interpreter like Maya. Maya 8.5 and later has a Python Interpreter built in so you could learn to use
Python inside the script editor of Maya.
There are different versions of the Python Interpreter. At the time of this writing, the latest version is
3.5.1. Maya 2016 uses Python 2.7. There are two main flavors of Python: the 3.x series and the 2.x
series. The 3.x series is the latest and greatest but the 2.x series is the most widely supported. You can
search online about the differences but Python 2.x is the what you’ll mostly encounter in the CG
industry.
5
www.chadvernon.com
FIGURE 1 – IDLE
6
www.chadvernon.com
7
www.chadvernon.com
To run this script from a command prompt or terminal window, you call the script with the python
command (which is on your system once you install Python).
D:\>C:\Python26\python myFirstPythonScript.py
You are running a python script.
8
You can add text together.
If you have the PATH environment variable (Google search “path environment variable”) set to include
Python (which should happen by default with the installer), you don’t need to specify the path to the
Python executable.
D:\>python myFirstPythonScript.py
You are running a python script.
8
You can add text together.
You can also route the output of your script to a file to save it for later use:
Another way to run a Python script is to open it in IDLE and run it from within the editor as shown
below. This is a great way to quickly experiment with Python code as you learn and write new scripts
and applications.
Shebang Lines
On Linux and OSX, you can use something called a shebang line to allow you to run a Python script
without having to specify python. For example, you could just run:
$> myFirstPythonScript.py
To use a shebang line, just add the following to the first lines of your script:
8
www.chadvernon.com
#!/usr/bin/env/ python
http://help.autodesk.com/view/MAYAUL/2016/ENU//?guid=__files_GUID_CB76E356_753B_4837_8C5B
_3296C14872CA_htm
Another way to add directories to the PYTHONPATH is to create a Maya.env file. The Maya.env file is a
file that modifies your Maya environment each time you open Maya. Place the Maya.env file in your
“My Documents\maya” folder.
9
www.chadvernon.com
Consult the Maya documentation for all the other variables you can set in the Maya.env file. If you have
multiple scripts with the same name in different directories, Python will use the first one it finds.
Notice when I import the module again, the script does not run:
10
www.chadvernon.com
Notice that when I reload the Python module, the result states it read the module from a .pyc file. A
.pyc file is a compiled Python file. When you import a Python module, Python compiles the code and
generates a .pyc file. You could distribute these .pyc files if you do not want people looking at your
code. Note however there are tools available on the internet that will easily decompile a pyc back into
source code. Import statements will work with .pyc files.
Python Modules
As you can see, Python modules are simply Python scripts that contain specific functionality. Since
Python is so widely used, you can find thousands of free Python modules on the internet that implement
various tasks such as networking, image manipulation, file handling, scientific computing, etc. To
interface with Maya, you import the maya.cmds module, which is the module that ships with Maya to
implement all the Maya commands.
Variables
The most common concept in almost all scripting and programming languages is the variable. A variable
is a storage container for some type of data:
11
www.chadvernon.com
FIGURE 9 – VARIABLES
Variables allow us to store data in order to use it later. Variables, sometimes called identifiers, must
start with a non-numeric character or underscore (_) and may contain letters, numbers, and
underscores (_). Identifiers are case sensitive. It is always a good idea to name your variables with
descriptive names so your code is easy to read.
joint_count finger.nail
button1 4vertexEdgeId
teeth_geometry cluster-handle
_particle_effect
Python is a dynamically typed language. This means that a variable can hold one type of value for a
while and then can hold another type later.
12
www.chadvernon.com
x = 5
x = 'Now x holds a string'
Not all languages allow you to do this. For example, in MEL, you have to declare a variable as an integer
and then that variable can only hold an integer. This is what is known as a statically typed language.
Integers Floating-point
43 1.324
-9234 -23.5325
6 6.2
Python supports all the math operators that you would want to use on these numbers.
x = 4 + 5 # Addition
y = x – 8 # Subtraction
y = y * 2.2 # Multiplication
z = y / 1.2 # Division
z = y // 3 # Floor division
z = z ** 4 # Power
z = -z # Negation
a = 10 % 3 # Modulus (division remainder)
x += 2 # Addition and store the result back in x, same as x = x + 2
x -= 2 # Subtraction and store the result back in x
x *= 2 # Multiplication and store the result back in x
x /= 2 # Division and store the result back in x
Notice in some of these statements, I use the same variable on both the right and left side of the
assignment operator (=). In most programming languages, the right side is evaluated first and then the
result is stored in the variable on the left. So in the statement y = y * 2.2, the expression
y * 2.2 is evaluated using the current value of y, in this case 1, and then the result (1 * 2.2) = 2.2 is
stored in the variable y.
Math operators have a precedence of operation. That is, some operators always execute before others
even when in the same expression. For example the following two lines give different results:
Multiplication and division always get evaluated before addition and subtraction. However, you can
control which expressions get evaluated first by using parentheses. Inner most parentheses always get
evaluated first.
13
www.chadvernon.com
When you mix integers and floating-point values, the result will always turn into a floating-point:
>>> 4 * 3.1
# Result: 12.4 #
Strings
Strings are text values. You can specify strings in single, double or triple quotes.
Single and double quoted strings are the same. The main thing to keep in mind when using strings are
escape sequences. Escape sequences are characters with special meaning. To specify an escape code,
you use the backslash character followed by a character code. For example, a tab is specified as ‘\t’, a
new line is specified as ‘\n’. You have to be mindful whenever escape sequences are involved because
they can lead to a lot of errors and frustration. For example, in Windows, paths are written using the
backslash: (e.x. C:\tools\new). If you save this path into a string, you get unexpected results:
Python reads the backslashes as an escape sequence. It thinks the ‘\t’ is a tab and the ‘\n’ is a new line.
To get the expected results, you either use escaped backslashes or a raw string:
The easiest thing to do in this case is to always use forward slashes for paths because Python will find
the right file whether on Windows or not.
14
www.chadvernon.com
Python will throw an error saying you cannot concatenate a string and an integer. You can fix this in a
couple different ways. One way is to convert the integer to a string.
String Formatting
String formatting allows you to code multiple string substitutions in a compact way. You use string
formatting with the format function available on all strings.
The format function allows you do automatically convert multiple variables into a string. The numbers
within the curly braces represent the index of argument within the format function.
15
www.chadvernon.com
You can also use the format function to control decimal precision, string alignment, as well as adding
zero-padding to strings. To read more about string formatting, visit
https://docs.python.org/2/library/string.html#format-string-syntax
To use the % operator, you provide a format string on the left of the % operator and the values you
want to print on the right of the % operator. Different types of values have different format codes.
Common codes include:
%s - string
%d, %i - integer
%f - floating-point
In the second example above, '%s%d' % (x, y) contains two format codes, a string followed by an
integer. On the right side of the % operator, we need to specify a value for each of the format codes in
the order they appear in the format string. String formatting not only lets us code in a more compact
way, it also lets us format values for output:
16
www.chadvernon.com
Like the format method, the % operator allows us to specify decimal precision, how many spaces a
number should be printed with, whether to include the sign, etc. This is especially useful when printing
out large tables of data. To read more about the % operator in string formatting, visit:
https://docs.python.org/2/library/stdtypes.html#string-formatting
I tend to prefer using the format method over the % operator because format is the more modern
method.
String Methods
Methods are chunks of code that perform some type of operation. We will learn more about methods,
also known as functions, in more detail later on, but now is a good time to introduce you to the syntax
of calling a method. We call a method using the dot operator (.):
object.method()
An object is an instance of a particular type. For example, we could have a string object.
When we read the code, some_object.some_method(), we say we are calling the method
named some_method from the object called some_object. Most objects have many callable
methods. The format method described in the previous section is a string method. Below are some of
the methods found in string objects:
Some of the methods have arguments in the parentheses. Many methods allow you to pass in values to
perform operations based on the arguments. For example x.replace('my', 'your') will return a
copy of string x with all of the 'my' instances replaced with 'your'. To view a list of the available
string methods, visit: https://docs.python.org/2/library/stdtypes.html#string-methods
There are many methods available for many different types of objects and there is no need to memorize
them. You will begin to memorize them after using them a lot. You can find help documentation for all
objects with the help command.
help(str)
17
www.chadvernon.com
The help command will print out the documentation associated with an object, class, or function.
Lists
Lists are sequences or arrays of data. Lists allow us to use organized groups of data in our scripts.
We can access elements in a list with a numeric index. The indices start at index 0 and increment with
each value in the list. We can also access subsets of lists with slicing
When an index is negative, it counts from the end of the list back. Lists can also contain mixed types of
data including other lists.
When you try to access an element that does not exist, Python will throw an error.
18
www.chadvernon.com
The concept of indexing is not unique to lists. We can actually access strings the same way.
You can think of strings as lists of characters. The main difference is strings cannot be edited in place
with indices. For example, the following is illegal.
Strings are what are known as immutable objects. Once they are created, they cannot be changed. Lists
on the other hand are mutable objects, meaning they can change internally.
Tuples
Tuples are the same as lists except they are immutable. They cannot be changed once created.
What is the purpose of tuples? There are aspects of Python that use or return tuples. I’d say 99.9% of
the time, you’ll be using lists. Just be aware that you cannot change a tuple when one eventually pops
up.
19
www.chadvernon.com
Dictionaries
Dictionaries are like lists except their elements do not have to be accessed with numeric indices.
Dictionaries are a type of look-up table or hash map. They are useful in storing unordered types of data.
20
www.chadvernon.com
Conditionals
To execute code only if a condition is True or False, you use the if, elif, and else statements.
The if statement runs a block of code (the indented portion) if the corresponding condition is True.
21
www.chadvernon.com
>>> x = 5
>>> if x == 5:
>>> x += 3
>>> print x
8
An if statement can have a corresponding else statement which runs if the condition in the if statement
is False.
>>> x = 5
>>> if x < 5:
>>> x += 3
>>> else: # Optional else
>>> x *= 2
>>> print x
10
>>> x = 5
>>> if x > 5 and not x == 2:
>>> x += 2
>>> elif x == 5: # Optional elif
>>> x += 4
>>> elif x == 9: # Optional elif
>>> x -= 3
>>> else: # Optional else
>>> x *= 2
>>> print x
9
if statements let you select chunks of code to execute based on boolean values. In a sequence of
if/elif/else statements, the first if statement is evaluated as True or False. If the condition is True,
the code in its corresponding code block is executed. If the condition is False, the code block is skipped
and execution continues to the next else or elif (else if) statement if one exists. else statements
must always be preceded by an if or elif statement but can be left out if not needed. elif
statements must always be preceded by an if statement but can left out if not needed.
Code Blocks
Code blocks are chunks of code associated with another statement of code. Take the following code for
example.
22
www.chadvernon.com
The last two lines are in the code block associated with the if statement. When the condition of the if
statement is evaluated as True, execution enters the indented portion of the script. Code blocks in
Python are specified by the use of whitespace and indentation. You can use any number of spaces or
even tabs, you just have to be consistent throughout your whole script. However, even though you can
use any amount of whitespace, the Python standard is 4 spaces. Code blocks can be nested in other
code blocks, you just need to make sure your indentation is correct.
>>> x = 5
>>> y = 9
>>> if x == 5 or y > 3:
>>> x += 3
>>> if x == 8:
>>> x *= 2
>>> elif y == 7:
>>> y -= 3
>>> if x == 16 or y < 21:
>>> x -= 10
>>> else:
>>> y *= 3
>>> else:
>>> x += 2
>>> print x
16
>>> print y
9
if/elif/else statements that are chained together need to be on the same indentation level. Read
though the previous example and work out the flow of execution in your head or on paper.
While Loops
While loops allow you to run code while a condition is True.
>>> x = 5
>>> while x > 1:
>>> x -= 1
>>> print x
4
3
2
1
In the above example, the condition is tested as True, so execution enters the code block of the while
loop. When execution reaches the print statement, the value of x has been decremented and execution
returns to the while statement where the condition is tested again. This loop continues until the
23
www.chadvernon.com
condition is False. You have to take care that the condition eventually evaluates to False or else you will
get an infinite loop.
>>> x = 5
>>> while x > 1:
>>> x += 1
In the above example, x will continue to increment and the condition will always be True. This is called
an infinite loop. If you create one of these, you’ll have to shut down your program, Ctrl-Alt-Delete, or
force quit out of Maya.
Sometimes you will want to exit out of a loop early or skip certain iterations in a loop. These can be
done with the break and continue commands.
>>> x = 0
>>> while x < 10:
>>> x += 1
>>> if x % 2:
>>> continue # When x is an odd number, skip this loop iteration
>>> if x == 8:
>>> break # When x == 8, break out of the loop
>>> print x
>>> else: # This optional else statement is run if the loop finished
>>> x = 2 # without hitting a break
2
4
6
>>> # This code causes an infinite loop, try to find out why.
>>> x = 0
>>> while x < 10:
>>> if x % 2:
>>> continue
>>> if x == 8:
>>> break
>>> print x
>>> x += 1
For Loops
For loops iterate over sequence objects such as lists, tuples, and strings. Sequence objects are data
types comprised of multiple elements. The elements are usually accessed by square brackets (e.g.
my_list[3]) as you’ve seen previously. However, it is often useful to be able to iterate through all of
the elements in a sequence.
24
www.chadvernon.com
You can iterate through two lists of the same length with the zip function.
Like the while loop, for loops support the continue, break, and else statements.
Functions
Previously, we’ve seen functions and methods built in to Python (such as range and zip) and built in to
different data types (string, list, and dictionary methods). Functions allow us to create reusable chunks
of code that we can call throughout our scripts. Functions are written in the form
25
www.chadvernon.com
Functions also accept arguments that get passed into your function.
>>>
>>> print_my_own_range(0, 5, 2)
0
2
4
26
www.chadvernon.com
Function Arguments
Function parameters (arguments) can be passed to functions a few different ways. The first is positional
where the arguments are matched in order left to right:
You can also specify the names of arguments you are passing if you only want to pass certain
arguments. These are called keyword arguments. This is the method used in the Maya commands.
Often you will see code where the arguments are unknown and both *arg and **kwargs will be used:
27
www.chadvernon.com
Scope
Scope is the place where variables and functions are valid. Depending on what scope you create a
variable, it may or may not be valid in other areas of your code.
1. The enclosing module (the .py file you create the variable in) is a global scope.
2. Global scope spans a single file only.
3. Each call to a function is a new local scope.
4. Assigned names are local, unless declared global.
Examples:
>>> x = 10
>>> def func():
>>> x = 20
>>>
>>> func()
>>> print x # prints 10 because the function creates its own local scope
>>> x = 10
>>> def func():
>>> global x
>>> x = 20
>>>
>>> func()
>>> print x # prints 20 because we explicitly state we want to use the global x
>>> x = 10
>>> def func():
>>> print x
>>> func() # prints 10 because there is no variable x declared in the local
# scope of the function so Python searches the next highest scope
Lambda Expressions
Lambda expressions are basically a way of writing short functions. Normal functions are usually of the
form:
28
www.chadvernon.com
This is useful because we can embed functions straight into the code that uses it. For example, say we
had the following code:
A drawback of this is that the function definitions are declared elsewhere in the file. Lambda
expressions allow us to achieve the same effect as follows:
>>> D = {
'f1': (lambda x: x + 1),
'f2': (lambda x: x - 1),
'f3': (lambda x: x / 2.2 ** 3.0)
}
>>> D['f1'](2)
Note that lambda bodies are a single expression, not a block of statements. It is similar to what you put
in a def return statement. When you are just starting out using Python in Maya, you probably won’t be
using many lambda expressions, but just be aware that they exist.
>>> x = [1,2,3]
>>> x[10]
Traceback (most recent call last):
File "<pyshell#107>", line 1, in <module>
x[10]
IndexError: list index out of range
29
www.chadvernon.com
>>> x = [1,2,3]
>>> try:
>>> x[10]
>>> except IndexError:
>>> print "What are you trying to pull?"
>>> print "Continuing program..."
Another variation includes both the else and finally statements, both of which are optional.
>>> x = [1,2,3]
>>> try:
>>> x[10]
>>> except IndexError:
>>> print 'What are you trying to pull?'
>>> else: # Will only run if no exception was raised
>>> print 'No exception was encountered'
>>> finally:
>>> print 'This will run whether there is an exception or not'
>>> print "Continuing program..."
You can raise your own exception if you want to prevent the script from running:
There are many different types of built-in exceptions that you can raise. You can even create your own
types of exceptions. To read more about the different types of built-in exceptions visit the
documentation here: https://docs.python.org/2/library/exceptions.html
RuntimeError
ValueError
TypeError
NotImplementedError
Modules
We learned in the beginning that Python modules are simply .py files full of Python code. These
modules can be full of functions, variables, classes (more on classes later), and other statements. We
also learned that to load a Python module from within Maya or another interactive prompt, we need to
import the module. When we import a module, we gain access to all the functionality of that module.
30
www.chadvernon.com
# mymathmodule.py
def add(x, y):
return x + y
import mymathmodule
mymathmodule.add(1, 2)
Or
import mymathmodule as mm
mm.add(1, 2)
Or
Or
Remember, we can only import a module once per Python session. If we were to update the code in
mymathmodule.py, we wouldn’t have access to the updates until we reload the module.
reload(mymathmodule)
We can also import modules into other modules. If we have one module full of some really useful
functions, we can import that module into other scripts we write (which are also modules) in order to
gain access to those functions in our current module.
Module Packages
Packages allow us to organize our Python modules into organized directory structures. Instead of
placing all of our modules into one flat directory, we can group our modules in subdirectories based on
functionality.
31
www.chadvernon.com
Any code you put in the __init__.py file of a package gets executed with the package. However, it is
usually good practice not to execute any complex code when the user imports your module or package.
32
www.chadvernon.com
There are also hundreds of third-party modules available online. For example, the PIL module contains
many functions that deal with image manipulation. To find out what functions are in a module, run the
help command or view online documentation.
Here’s a more practical example of opening a maya ascii file and renaming myBadSphere to
myGoodSphere.
Python also makes it easy to find files and traverse directory hierarchies.
33
www.chadvernon.com
x = 'happy'
x.capitalize() # returns Happy
x.endswith('ppy') # returns True
x.replace('py', 'hazard') # returns "haphazard"
x.find('y') # returns 4
You are free to use Python without using any of its object oriented functionality by just sticking with
functions and groups of statements as we have been doing throughout these notes. However, if you
would like to create larger scale applications and systems, I recommend learning more about object
oriented programming. The Maya API and PyMEL, the popular Maya commands replacement module,
are built upon the notions of object oriented programming so if you want to use API functionality or
PyMEL in your scripts, you should understand the principles of OOP.
Note that while I give a brief introduction to object-oriented programming in this paper, a few pages
cannot do the topic any justice. I recommend reading more about object-oriented programming in the
endless resources found online and in books.
Classes
Classes are the basic building blocks of object oriented programming. With classes, we can create
independent instances of a common object. It is kind of like duplicating a cube a few times. They are all
cubes, but they have their own independent attributes.
34
www.chadvernon.com
class Shape(object):
def __init__(self, name):
self.name = name
def print_me(self):
print 'I am a shape named {0}.'.format(self.name)
The above example shows a simple class that contains one data member (name), and two
functions. Functions that begin with a double underscore usually have a special meaning in Python. The
__init__ function of a class is a special function called a constructor. It allows us to construct a new
instance of an object. In the example, we create two independent instances of a shape object: shape1
and shape2. Each of these instances contains its own copy of the name attribute defined in the class
definition. In the shape1 instance, the value of name is “myFirstShape”. In the shape2 instance, the
value of name is “mySecondShape”. Notice we don’t pass in any value for the self argument. We don’t
pass in any value for the self argument because the self argument refers to the particular instance of a
class.
The first argument in all class member methods (functions) should be the self argument. The self
argument is used to represent the current instance of that class. You can see in the above example
when we call the print_me method of each instance, it prints the name stored in each separate
instance. So objects are containers that hold their own copies of data defined in their class definition.
35
www.chadvernon.com
def print_me(self):
super(PolyCube, self).print_me()
# The .2f in the string format means use 2 decimal places
print 'I am also a cube with dimensions {0:.2f}, {1:.2f},
{2:.2f}.'.format(self.length, self.width, self.height)
class PolySphere(Shape):
def __init__(self, name, radius):
# Call the constructor of the inherited class
super(PolySphere, self).__init__(name)
def print_me(self):
super(PolySphere, self).print_me()
print 'I am also a sphere with a radius of {0:.2f}.'.format(self.radius)
In the above example, we create two new classes, PolyCube and PolySphere, that inherit from the base
class, Shape. We tell a class to inherit from another class by placing the class to inherit from in
parentheses when we declare the derived class. The two new classes will have all the data and methods
associated with the shape base class. When we call the constructor method, __init__, of PolyCube and
PolySphere, we still want to use the functionality of the constructor of its super class, shape. We can
36
www.chadvernon.com
The previous example is an extremely simplified version of Maya’s architecture. Nodes inherit off of
other nodes to build a complex hierarchy. Below is part of Maya’s object oriented node hierarchy:
Python supports a method of creating documentation for your modules known as docstrings. Docstrings
are strings written with triple quotes (“””) and can be placed at the top of modules and inside functions.
37
www.chadvernon.com
When you type help(modulename), Python will print some nice documentation using the docstrings that
you specified in your module.
There is an official specification on how you should format your docstrings, called the PEP 0257 which
you can read about here: https://www.python.org/dev/peps/pep-0257/. Many people don't strictly
follow this format and use a format that is supported by documentation generation tools like Doxygen,
Epydoc, and Sphix. Formats include (taken from http://stackoverflow.com/questions/3898572/what-is-
the-standard-python-docstring-format):
38
www.chadvernon.com
Epytext
"""
This is a javadoc style.
reST
"""
This is a reST style.
Google
"""
This is an example of Google style.
Args:
param1: This is the first param.
param2: This is a second param.
Returns:
This is a description of what is returned.
Raises:
KeyError: Raises an exception.
"""
Numpydoc
39
www.chadvernon.com
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
when an other error
"""
I recommend using one of these widely used formats instead of making one up on your own. You
should try to put docstrings in your code as much as possible. It will save you and your coworkers a lot
of time down the road.
Coding Conventions
Unlike many other languages, Python has an official coding convention called the PEP8 standard. A
coding convention describes the style rules and format of your code. It is by no coincidence that all the
code examples listed so far use underscore_separated variable and function names, four spaces for
indentations, and CaptilizedCamelCase for class names. These conventions are all part of the PEP8
standard. You'll notice however that Maya does not follow the PEP8 standard. The main reason for this
is that the Python API is generated procedurally from the C++ API. When writing Python code, I highly
encourage you to follow the PEP8 standard even if you prefer or have used a different convention in the
past.
Most of the Python world uses the PEP8 standard. Do not do what Maya does, instead use the official
and accepted standard. The only time not to follow PEP8 conventions (as noted in PEP8 itself) is to
follow the standard of the existing codebase you are working with. You do not need to follow every
single little rule, just be consistent.
You can read more about the PEP8 standard here: https://www.python.org/dev/peps/pep-0008/
40
www.chadvernon.com
# Variable names
skin_joints = ['joint1', 'joint2'] # Yes
skinJoints = ['joint1', 'joint2'] # No
# Function names
def calculate_bounds(): # Yes
def calculateBounds(): # No
# Spacing
[1, 2, 3, 4] # Yes
[1,2,3,4] # No
get_export_nodes(root='skeleton_grp') # Yes
get_export_nodes( root = 'skeleton_grp' ) # No
In this section, I'll give brief pointers on how to make your code cleaner and easier to read. For more in-
depth discussions on writing clean code, I recommend the excellent book, " Clean Code: A Handbook of
Agile Software Craftsmanship", by Robert C Martin, and the Pluralsight course, " Clean Code: Writing
Code for Humans" by Cory House.
41
www.chadvernon.com
sphere = create_poly_sphere(name='left_eye')
assign_shader(sphere, 'blinn1')
parent_constrain(head, sphere)
sphere = create_poly_sphere(name='right_eye')
assign_shader(sphere, 'blinn2')
parent_constrain(head, sphere)
create_eye('left_eye', 'blinn1')
create_eye('right_eye', 'blinn2')
The second code example is easier to maintain. If an update needs to be implemented, we only have to
update code in one place rather than multiple places.
curr= os.environ.get('CURRENT_CONTEXT')
if curr:
cl= curr.split('/')
self.__curr= [None] * 6
self.setType( cl[0] )
self.setSeq( cl[1] )
if len( cl ) > 3:
self.setSubseq( cl[2] )
self.setShot( '/'.join( cl[2:] ) )
else:
self.setShot( cl[-1] )
if wa: self.__wa= wa
else: self.__wa= os.environ.get('CURRENT_WORKAREA')
Can you tell what this code is doing? If you're familiar with writing pipeline environment tools, you
might recognize what it is trying to do. What is self.__curr? Why is it a list of 6 values? What do the
elements of cl repreprent? Why does the length of cl being greater than 3 differentiate one block of the
if statement from the other?
42
www.chadvernon.com
The above code cleans up all the list indices and string manipulations to make the code easier to read
and understand. The individual list elements have been assigned meaningful names. Also the
environment variable accesses have been extracted away into new methods. This makes the code
easier to maintain. What happens if we want to change the name of the environment variables or
maybe we want to read the values from a configuration file on disk? Extracting those values to
functions would let us update the code in one place rather than multiple direct accesses to the
environment variable.
Naming Classes
Class names should be a noun because they represent objects. The name should be as specific as
possible. If the name cannot be specific, it may be a sign that the class needs to be split into smaller
classes. Classes should have a single responsibility.
Naming Methods
Method names should be verbs because they perform actions. There should be no need to read the
contents of a method if the name accurately describes what the method does. If the function is doing
one thing (as it should) it should be easy to name. If not, split the code into smaller functions.
Sometimes explaining the code out loud and help you name the function. If you say "And", "If", or "Or"
it is a warning sign that the method is doing too much.
proc_new create_process
pending is_pending
process1 send_notification
process2 import_mesh
calculate_rivet_matrix
Methods should only perform the actions described by the name. Any other actions are called side
effects and they can confuse people using your code. For example, a method called validate_form
43
www.chadvernon.com
should not save the form. A method called publish_model should not smooth the normals. A method
called prune_weights should not remove unused influences.
Avoid Abbreviations
Abbreviated text may be easier to type, but code is read more than it is written. When people talk
about code or read it silently, it is harder to say the abbreviations. There are also no standards when
referring to abbreviations.
sjData subjob_data
jid job_id
sjid subjob_id
nm name
sjState subjob_state
Naming Booleans
Boolean values should be able to fit in an actual sentence of saying something is True or False.
open is_open
status logged_in
login is_valid
enabled
done
Symmetrical Names
When names have a corresponding opposite, be consistent and always use the same opposite.
on/disabled on/off
quick/slow fast/slow
lock/open lock/unlock
low/max min/max
# Don't do this
if (is_valid == True):
# do something
# Instead do this
if (is_valid):
# do something
44
www.chadvernon.com
# Don't do this
if len(items) == 0:
remove_entry = True
else:
remove_entry = False
# Instead do this
remove_entry = len(items) == 0
Avoid using booleans that represent negative values. This leads to double negatives, which end up
confusing people:
# Don't do this
if not not_valid:
pass
# Instead do this
if valid:
pass
Use Ternaries
Ternaries are ways of assigning a value to a variable depending on if some condition is True or False. For
example:
# Don't do this
if height > height_threshold:
category = 'giant'
else:
category = 'hobbit'
# Instead do this
category = 'giant' if height > height_threshold else 'hobbit'
if component_type == 'arm':
# do something
elif component_type == 'leg':
# do something else
This is considered bad form for various reasons. If we end up wanting to change the value of one of
these types, we have to change it in all the places that it is used. It can also lead to typos and
inconsistencies. A better approach would be:
45
www.chadvernon.com
class ComponentType(object):
arm = 'arm'
leg = 'leg'
if component_type == ComponentType.arm:
# do something
elif component_type == ComponentType.leg:
# do something else
The new code provides one place to change and update values (the DRY principle). It also provides
auto-completion support and is more searchable if you are using an IDE like PyCharm or Eclipse.
if run_mode < 3:
run_mode = 5
elif run_mode == 3:
run_mode = 4
What do these numbers mean? You would need to search all over code that could span multiple files to
figure out what these numbers represent. A better approach would be:
class JobStatus(object):
waiting = 1
starting = 2
running = 3
aborting = 4
done = 5
def not_yet_running(self):
return self.status < JobStatus.running
def abort(self):
if self.not_yet_running():
self.status = JobStatus.done
elif self.status == JobStatus.running:
self.status = JobStatus.aborting
46
www.chadvernon.com
# Instead of this
if (obj.component.partial_path.startswith('model') and
namespace == ‘GEOM’ and
has_rigging_publish(obj.child) and
edits_path):
if is_model_only_publish(obj):
Extracting a Method
If you find your code 3 or 4 indentation levels deep, it may be time to extract some of that code into a
separate function. For example:
# Instead of this
if something:
if something_else:
while some_condition:
# do something complicated
# Do this instead
if something:
if something_else:
do_complicated_things()
def do_complicated_things():
while some_condition:
# do something complicated
Return Early
People can usually only keep track of a handful of trains of thought at a time. Therefore, we should try
to organize our code is as many discrete independent chunks as possible. For example:
47
www.chadvernon.com
# Instead of this
def validate_mesh(mesh):
result = False
if has_uniform_scale(mesh):
if has_soft_normal(mesh):
if name_is_alphanumeric(mesh):
result = name_is_unique(mesh)
return result
# Do this
def validate_mesh(mesh):
if not has_uniform_scale(mesh):
return False
if not has_normal(mesh):
return False
if not name_is_alphanumeric(mesh):
return False
return name_is_unique(mesh)
This is not a strict rule. Like everything listed so far, use it when it enhances readability.
Chapter Module
o Heading 1 o Class 1
Paragraph 1 Method 1
Paragraph 2 Method 2
o Heading 2 o Class 2
Paragraph 1 Method 1
High Cohesion
Cohesion is the fact of forming a united whole. When a class is said to have high cohesion, all of its
functionality is closely related. We should strive to create classes with high cohesion. High cohesion not
only enhances readability; it also increases the likelihood of reusing the class. Signs that a class does not
have high cohesion are:
The class has methods that don't interact with the rest of the class.
48
www.chadvernon.com
For example:
def edit_options():
pass
def update_pricing():
pass
def schedule_maintenance():
pass
def send_maintenance_reminder():
pass
def select_financing():
pass
def calculate_monthly_payment():
pass
The Vehicle class contains many unrelated methods. This makes it harder to use and maintain because
parts of unrelated code are intertwined together. A better approach would be to split this class up into
smaller classes:
49
www.chadvernon.com
def edit_options():
pass
def update_pricing():
pass
class VehicleMaintainer(object):
def schedule_maintenance():
pass
def send_maintenance_reminder():
pass
class VehicleFinancer(object)
def select_financing():
pass
def calculate_monthly_payment():
pass
Method Proximity
Code should read top to bottom and related methods should be kept together:
def add_take():
if not validate_take(): # First method referenced should be directly below
raise ValueError('Take is not valid')
save_take() # Second method referenced should be below first
def validate_take():
return take.endswith(‘.mov’)
def save_take():
# save in database
Collapsed code should read like an outline. Strive for multiple layers of abstraction:
Class
o Method 1
Method 1a
Method 1ai
Method 1aii
Method 1b
Method 1c
o Method 2
Method 2a
50
www.chadvernon.com
Comments
Comments should only be used to explain ideas and assumptions not already apparent by reading the
code.
Redundant Comments
The comments in this code do not add anything the user could not have figured out by reading the code.
Divider Comments
If you see divider comments, it's a sign you need to extract the code into its own function:
51
www.chadvernon.com
# Now create the new group object and insert it into the table
# ----------------------------------------------------------------------------------
# Create the group object
group = slidergroup.SliderGroup(name)
self._slider_groups[name] = group
# Tell the group what its start row is
group.setRow(row)
# Apply color
if color:
group.setColor(color)
Zombie Comments
Zombie comments are large sections of commented out code. People often do this because they think
they might need the code in the future. This is unnecessary because version control systems like git,
svn, and perforce perform this exact functionality. People looking at code with large commented out
portions will be confused. Why is the code commented out? Is it important?
52
www.chadvernon.com
Python in Maya
Maya’s scripting commands come in the module package maya.cmds.
import maya.cmds
You will notice that if you type in help(cmds), you do not get anything useful besides a list of function
names. This is because Autodesk converted all of their MEL commands to Python procedurally. To get
help with Maya’s Python commands, you will need to refer to the Maya documentation.
53
www.chadvernon.com
what you are trying to accomplish with Maya’s interface and look at the script editor. Most the actions
you do with the Maya interface output what commands were called in the script editor. The only caveat
is that the output is in MEL so we’ll have to do a little bit of translating. Since all of the commands and
arguments are the same between the MEL and Python commands, translating between the two is pretty
easy.
Creating a polygon sphere outputs the following MEL command into the script editor:
MEL commands usually consist of the command name followed by several flags. In the above code,
polySphere is the command, and each group of letters following a “-“ is a flag. The numbers after each
flag are arguments of their corresponding flag. For example, “-r” is a flag with an argument of 1, “-sx”
is a flag with an argument of 20, “-ax” is a flag with 3 arguments: 0, 1, 0. Using this information, we can
look up the command in the Maya Python command documentation and write its Python equivalent.
Like I said earlier, commands in MEL and Python have the exact same name, look up “polySphere” in
the Python documentation. It looks like this:
54
www.chadvernon.com
The documentation page contains all the information you need to work with the command. The
Synopsis shows the function and all the possible arguments that can be passed in along with a
description of what the command does. In this case, it creates a new polygonal sphere. The return
value tells us what the function returns. The polySphere command returns a list containing two strings.
The first element of the list will be the name of the transform of the new polygon sphere. The second
string in the list will be the name of the polySphere node, which controls how the sphere is constructed.
>>> x = cmds.polySphere()
>>> print x
[u'pSphere1', u'polySphere1']
Notice that each string has a ‘u’ before it. This stands for Unicode string which is a type of string that
you can ignore for now. Unicode strings help with international languages so just assume they are the
same as normal strings.
Following the Return value section is a list of related Maya Commands. Following these links is a good
way to learn about other commands. After the related commands is the Flags section. This section
should really be called Arguments or Parameters; Flags are more of a MEL construct. The list of Flags
(arguments) contains all the arguments that can be passed into the documented function. Each
argument description contains the argument name, an abbreviated argument name, what kind of data
you can pass into the argument, in what context the argument is valid, and a description of the
argument. Take the radius argument for example. By passing this argument to the polySphere function,
we can control the radius of the created sphere.
>>> x = cmds.polySphere(radius=2.5)
>>> x = cmds.polySphere(r=2.5)
>>> print x
[u'pSphere2', u'polySphere2']
Personally, I tend to avoid the abbreviated form as I can never remember what all the abbreviations
mean when I read my code. Using the full name is more typing and makes your code longer, but I find it
easier to read.
The documentation is not always clear about what type of data is expected with an argument. For
example, the documentation says that the radius argument expects some data of type linear. Usually
by looking at the equivalent MEL command, you can figure out what to pass into the Python command.
However, there are some cases where the documented format of the expected data is just really vague
or cryptic. In these cases, if you can’t figure out how to format the command, ask on a forum or mailing
list.
After the list of arguments, there is usually an examples section that gives various usage examples of the
given command.
55
www.chadvernon.com
we can see that each of the MEL flags corresponds to an argument in the Python function. By looking up
the flags in the Python documentation, we can write the equivalent Python command:
It’s up to you on whether to use the abbreviated flags or not. Note that I also swapped the ch=1 for
ch=True. Refering to the documentation, the constructionHistory argument expects a Boolean value.
Remember from the Booleans and Comparing Values section that all non-zero numbers are evaluated as
True. I like to actually pass in the value True (or False if you want False) to these types of arguments
just for my own preference.
You will also notice in the documentation the letters in the colored squares. The C, Q, M, and E stand
for Create, Query, Multiple, and Edit. These letters tell you in what context an argument is valid. Many
commands have different functionality depending on what context you are running the command in. In
the previous example, we were creating a sphere, so all the arguments marked C were valid.
When you run a command in query mode, you can find information about an object created with the
same command. You run a command in query mode by passing query=True as an argument.
When you query a command, you pass in the object you want to query first, followed by your
arguments. When in query mode, you pass a True or False to the argument you want to query
regardless of what the expected type for that argument is documented as. You should only query one
argument at a time. You’ll notice that when you query a value, the value returned from the function
may not be the same as what the documentation says is returned. In create mode, the polySphere
command returns a list of 2 strings. In query mode, the return type depends on the value you are
querying.
Besides create and query modes, you can also run a command in edit mode. Edit mode lets you edit
values of an existing node created with the command. You run a command in edit mode by passing in
edit=True as an argument to the function.
56
www.chadvernon.com
And finally, sometimes a flag is marked with being available multiple times. For example the curve
command has point argument (p) that we use to specify all the cv's of a curve.
# MEL
curve -p 0 0 0 -p 3 5 6 -p 5 6 7 -p 9 9 9 -p 0 0 0 -p 3 5 6;
# Python
cmds.curve(p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9), (0, 0, 0), (3, 5, 6)])
You now know how to look up command syntax and decipher the documentation. You have just about
all the knowledge you need now to write your own Maya scripts in Python. All you need now is to learn
the various commands. A really good way to do that is to look at other people’s scripts.
Sample Scripts
In most of the sample scripts, you will notice that I always put the code in functions or classes. When
you import a module, all of the code in the module gets executed. However, code inside functions does
not get run until the function is called. When writing scripts for Maya, it is good practice to structure
your code as functions or classes to be called by users. Otherwise, you may surprise your users by
executing unwanted code when they import your modules.
lightintensity.py
57
www.chadvernon.com
def scale_light_intensity(percentage=1.0):
"""Scales the intensity of each light in the scene by a percentange.
Concepts used: functions, lists, for loops, conditional statements, string formatting
In the function docstring, I list the argument with "@param". This is a format compatible with
documentation generation tools such as Doxygen which can generate documentation based off of this
format. There are a few other docstring conventions out there, choose one and be consistent.
import lightintensity
lightintensity.scale_light_intensity(1.2)
renamer.py
58
www.chadvernon.com
@param name: A renaming format string. The string must contain a consecutive
sequence of '#' characters
@param nodes: List of root nodes you want to rename. If this argument is
omitted, the script will use the currently selected nodes.
"""
# The variable "nodes" has a default value of None. If we do not specify a value
# for nodes, it will be None. If this is the case, we will store a list of the
# currently selected nodes in the variable nodes.
if nodes is None:
# The ls command is the list command. Get all selected nodes
# of type transform.
nodes = cmds.ls(sl=True, type='transform')
# Find out how many '#' characters are in the passed in name.
digit_count = name.count('#')
if digit_count == 0:
raise RuntimeError('Name has no # sequence.')
# We need to verify that all the '#' characters are in one sequence.
substring = '#' * digit_count # '#' * 3 is the same as '###'
newsubstring = '0' * digit_count # '0' * 3 is the same as '000'
# The replace command of a string will replace all occurances of the first
# argument with the second argument. If the first argument is not found in
# the string, the original string is returned.
newname = name.replace(substring, newsubstring)
59
www.chadvernon.com
# Start at number 1
number = 1
for node in nodes:
# Loop through each selected node and rename its child hierarchy.
number = rename_chain(node, name, number)
# Since we renamed the current node, we increment the number for the next
# node to be renamed.
number += 1
for child in children:
# We will call the rename_chain function for each child of this node.
number = rename_chain(child, name, number)
return number
Concepts used: functions, recursive functions, lists, for loops, conditionals, string formatting, exceptions.
To run this script, select the root joint of a joint chain and in the script editor type:
import renamer
renamer.rename('C_tail##_JNT')
The renamer script uses a concept called recursive functions. A recursive function is a function that calls
itself. Recursive functions are useful when you are performing operations on data in a hierarchical
graph, like Maya’s DAG. In recursive functions, you must specify an ending condition or else the
function will call itself in an infinite loop. In the above example, the function calls itself for each child
node in the hierarchy. Since there are always a limited number of children in a Maya hierarchy, the
recursive function is guaranteed to stop at some point.
60
www.chadvernon.com
61
www.chadvernon.com
mayapy X:\file.py
You can also write scripts to run operations on Maya files in batch mode.
Example: Open a Maya file, assign the default shader to all meshes, and save the scene.
import maya.standalone
import maya.cmds as cmds
def assign_default_shader(file_path):
# Start Maya in batch mode
maya.standalone.initialize(name='python')
In order to run this script, you need to use the mayapy Python interpreter and not the normal Python
interpreter. In addition to stand alone scripts, I recommend reading about the argparse module which
would allow you to start the mayapy interpreter and call the script all in one line from the command
line.
Further Reading
While I've covered most of the basics, there are still many more aspects of Python and programming in
general.
Clean Code: A Handbook of Agile Software Craftsmanship is a great book on reading clean and easy to
read code. While not Python specific (it's written for Java) it's concepts still apply.
http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
62
www.chadvernon.com
Conclusion
After reading these notes, you should have a good understanding of how to write and run Python scripts
inside and outside of Maya. There is still plenty to learn though. There are hundreds of Maya
commands and plenty of useful modules out there to experiment with. I recommend continuing your
Python education by looking through the references included with these notes, reading other peoples’
scripts, and experimenting with your own scripts. Good luck!
63