0

**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  
Green Cell
  • 4,677
  • 2
  • 18
  • 49
winteralfs
  • 459
  • 6
  • 25

2 Answers2

2

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')
Daniel Skovli
  • 455
  • 3
  • 8
  • Thank you, I would I use try,except with the nodeType command? My mind keeps going to if, else... Because try does not have a condition check in its line. Also, what exception error would it be throwing if it is not a file node? – winteralfs Jul 16 '20 at 22:24
  • 1
    The nodeType command will only throw errors (like most Maya functions) if you feed it incorrect or unsolvable node names. I haven't actually tested this, but that's how most of the `cmds` commands work. In reality though, if you're grabbing a user's selection you are pretty safe for this type of command. I have updated my answer to address your question a bit more thoroughly – Daniel Skovli Jul 16 '20 at 22:33
-1

You might be over complicating this. If all you want to do is check to see if a list of nodes are a file type then it could be done in almost a one-liner:

import maya.cmds as cmds

def is_node_type(objs, node_type="file"):
    return len(cmds.ls(objs, type=node_type)) > 0

is_node_type(cmds.ls(sl=True))  # Check with current selection.

You can pass a list of objects to cmds.ls and specify the parameter type to whatever you want to check. Returning the length of that directly will return True if that type exists in the collection of objects, or False if it doesn't. Since the function also has node_type parameter you can easily change it to something else without hard-coding it.

At that point you can do whatever you want with it. Generally you can stick with if else conditions. Though some cases might be long winded when you nest many if statements, so in that case you can predict errors that might arise and catch it with try except. I believe this is like EAFP (Easier to ask for forgiveness than permission). There are some cases where you have no choice but to use try, and this is usually when external factors are involved, like relying on your internet connection or connecting to some server that may be down.

Green Cell
  • 4,677
  • 2
  • 18
  • 49
  • Not sure, but my take on this question is that OP is obviously new to programming, or at least Python. So emphasis on readability seems more valuable than one-liners and otherwise optimised-but-hard-to-read code. – Daniel Skovli Jul 19 '20 at 01:39