Python Recursion Limit

While executing third party plugins or your own plugins which is written in python, have you ever faced the “maximum recursion depth exceeded” error? Python lacks the tail recursion optimizations common in functional languages like LISP.

Recur-limit

Let’s say, you want to add the specified node to the node array in FBX using recursive function, we can use the below approach to travel the whole scene. However, if your scene contains more than 1000 nodes, you will get the recursion limit issue(maximum recursion depth exceeded). .

# Add the specified node to the node array. Also, add recursively
# all the parent node of the specified node to the array.
def AddNodeRecursively(pNodeArray, pNode):
if pNode:
AddNodeRecursively(pNodeArray, pNode.GetParent())
found = False
for node in pNodeArray:
if node.GetName() == pNode.GetName():
found = True
if not found:
# Node not in the list, add it
pNodeArray += [pNode]

So, you have to use sys.setrecursionlimit() method to fix this issue in python.

# Add the specified node to the node array. Also, add recursively
# all the parent node of the specified node to the array.
import sys
sys.setrecursionlimit(5000)
def AddNodeRecursively(pNodeArray, pNode):
if pNode:
AddNodeRecursively(pNodeArray, pNode.GetParent())
found = False
for node in pNodeArray:
if node.GetName() == pNode.GetName():
found = True
if not found:
# Node not in the list, add it
pNodeArray += [pNode]

Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading