Search code examples
pythonmaya

using try, except with Maya Python to check to make sure items in a selection are the correct node type


**I am struggling with how to know when to use try/except verses if/else when checking the node types of selected nodes, and how to use try/except in a situation like below.

I want to do something like this:**

selected_nodes = cmds.ls(sl = True)

for selected_node in selected_nodes:

    #example one

    validate_node_type = validate_nodes(selected_node)
        if validate_node_type == True
            return True
        else:
            return False

    def validate_nods(selected_node):
        node_type = cmds.node_type(selected_node)
        if node_type == 'file':
            return True
        else:
            return False
    
    #example two, or is better to use try/except?

    try:
        validate_nodes(selected_node)
        return True
    except:
        return False
    
    def validate_nodes(selected_node):
        selected_node_type = nodeType(selected_node)
        try:
            selected_node_type == 'file'
            return True
        except:
            return False  

Solution

  • In short, you would use if/else to perform a logical check, and try/except to wrap code that might throw an error and prevent the rest of your code from executing.

    In your specific example, node_type = cmds.nodeType(selected_node) might throw an error, so if you're going to use try/except anywhere, this is probably the place.

    Sometimes though, throwing an error is completely the right thing to do -- especially if the operation is not unattended.

    Personally, I would refactor your code to look like this:

    def validate_fileNodes(nodes):
        '''Check if a single or list of objects are of type `file`
        
        Args:
            nodes (str|list [str]): Nodes to check
    
        Returns:
            bool: True if all matches, False otherwise
        '''
    
        if not isinstance(nodes, (list, tuple)):
            nodes = [nodes]
        
        for node in nodes:
            if cmds.nodeType(node) != 'file':
                return False
    
        return True
    
    selected_nodes = cmds.ls(sl=True)
    valid_files = validate_fileNodes(selected_nodes)
    
    print('Selected nodes are valid files? {}'.format(valid_files))
    

    Keeping in mind that this may throw an error if you feed it bad info, but how you handle that should probably be dealt with outside of your validation function.

    Edit: In answer to comments, to catch errors I would do it here:

    selected_nodes = cmds.ls(sl=True)
    valid_files = None
    
    try:
        # This method may raise an error, but we catch it here instead of in the method itself
        valid_files = validate_fileNodes(selected_nodes)
    except Exception as e:
        print('validate_fileNodes method raised an exception: {}'.format(e))
    
    if valid_files == True:
        print('Selected nodes are valid!')
    elif valid_files == False:
        print('Selected nodes are not valid, but the check went well')
    else:
        print('The check failed. We dont know whats going on here')