Maya Python print to output window Create your own user preferences file using Maya Python
Dec 16

I thought it worth a post on how eval works in Python. Somone posted a question on cgtalk about how they tried to use eval inside of a Python class and they received errors. They tried to test the code by executing the string in the script editor which worked. The problem is that eval is not for executing code it is for executing expressions. Here is some Python code as an example. Just run this in your Maya Python tab.

import maya.mel as mel
import maya.cmds as cmds

# Mel eval test
def meleval():
	mel.eval('float $foo = 10;')

meleval()

# switch to the mel tab and type:
print $foo;

# this prints 10

# Switch back to the Python tab
# Now try python eval, which is for expressions
print eval( '1+1' )

# prints 2

# Try to get more complicated with eval though and this happens:
eval( 'foo = 10' )

# Error: ('invalid syntax', ('', 1, 5, 'foo = 10'))
# Traceback (most recent call last):
#   File "", line 1, in
# SyntaxError: ('invalid syntax', ('', 1, 5, 'foo = 10')) # 

# so what do you use?
def pyexec():
	exec( 'foo = 10' )
	print foo

pyexec()

# prints 10

# now try to print foo like you did with MEL eval
print foo

# Error: name 'foo' is not defined
# Traceback (most recent call last):
#   File "", line 1, in
# NameError: name 'foo' is not defined # 

# Now why is this?
# The exec executes in the scope that it is executed in
# You can get around this though:

def pyexecglobal():
	exec( 'foo = 5' ) in globals()
	exec( 'foob = 5' ) in locals()
	print foo
	print foob

pyexecglobal()

# Now try:
print foo

# success

print foob

# Error: name 'foob' is not defined
# Traceback (most recent call last):
#   File "", line 1, in
# NameError: name 'foob' is not defined #

So exec is what you want.

-RyanT

Leave a Reply