I always kept running into problems when making PyNodes in my script and the error messages Maya gives you aren’t always the best. So I wrote a little helper function, especially useful when you have more than one object with the same name in your scene.

def pynode(object_name, specific_on_multiple=False, pick_most_root=False, pick_most_leaf=False, pick_index=None):
    """
    Returns a PyNode of the given object name with better error messages and additional options
 
    :param object_name: name of the object you want to make a PyNode
    :param specific_on_multiple: <bool> When set to True, allows you set the next flags to return a specific object when there are multiple objects with the same name
    :param pick_most_root: <bool> returns the most root object if there are multiple objects with the same name
    :param pick_most_leaf: <bool> returns the most leaf object if there are multiple objects with the same name
    :param pick_index: <int> returns this index of object if there are multiple objects with the same name
    :return: a PyNode
    """
    if object_name is None:
        raise RuntimeError("Can't make a PyNode when object_name type is None")
    if pm.objExists(object_name):
        try:
            return pm.PyNode(object_name)
        except:
            if not type(object_name) == str:
                node_name = object_name.nodeName()
            else:
                node_name = object_name
            multiple_nodes = sorted([str(node) for node in pm.ls(node_name)], key=len)
 
            if len(multiple_nodes) > 1:
                if specific_on_multiple is False:
                    error_message = "There are multiple nodes with this name:"
                    for node in multiple_nodes:
                        error_message += "\n%s" % node
                    raise RuntimeError(error_message)
                else:
                    if pick_most_root is True:
                        return pm.PyNode(multiple_nodes[0])
                    elif pick_most_leaf is True:
                        return pm.PyNode(multiple_nodes[-1])
                    elif pick_index is not None:
                        try:
                            selected_node = multiple_nodes[pick_index]
                        except IndexError:
                            raise IndexError("%s is not a valid index, valid indices are 0 to %s"
                                             % (pick_index, len(multiple_nodes) - 1))
                        return pm.PyNode(selected_node)
 
                    raise ValueError("When custom_on_multiple is set to True, either pick_most_root or pick_most_leaf "
                                     "should be set to True as well")
    else:
        raise ValueError("Object (%s) doesn't exist" % object)