Force Refresh Expressions

Expressions can be a pain as they don’t always get evaluated. This is particularly problematic if you want to use an environment variable to control a switch node.
So, how do we force nuke to re-evaluate expressions? Looking at the properties of the switch-node, there’s nothing like “evaluate”, and even using getValue() doesn’t force the expression to re-evaluate even though we actually get the right value back from the python call.

The trick is to get the expression from the node, and re-apply it. This triggers the node to re-evaluate the switch value.
You can achieve this with the following python:


[a['which'].fromScript(nuke.allNodes('Switch')[0]['which'].toScript()) for a in nuke.allNodes('Switch')]

The builtin allNodes() method doesn’t handle groups very well, so you might want to replace it with this method instead (kindly shared by Sean Wallitsch : http://shidarin.github.io/2014/building-a-better-nukeallnodes/


def allNodes(filter=None, group=nuke.root(), recurseGroups=False):
    """ Wraps nuke.allNodes to allow filtering and recursing
    
    Args:
        filter=None : (str)
            A Nuke node name to filter for. Must be exact match.
        
        group=nuke.root() : ()
            A Nuke node of type `Group` to search within. If not provided, will
            begin the search at the root level.
        
        recurseGroups=False : (bool)
            If we should continue our search into any encountered group nodes.
    
    Returns:
        []
            A list of any Nuke nodes found whose Class matches the given filter.
    
    Raises:
        N/A
    
    """
    # First we'll check if we need to execute our custom allNodes function.
    # If we don't have a filter AND recurseGroups=True, `nuke.allNodes` will
    # do the job fine.
    if filter and recurseGroups:
        # Search for every node, then filter using a list comprehension.
        # Faster than searching for all groups, then searching again
        # for the filter.
        all_nodes = nuke.allNodes(group=group, recurseGroups=True)

        return [node for node in all_nodes if node.Class() == filter]

    else:
        # We just need to execute Nuke's `nuke.allNodes` function.
        # But we need to modify our list of keyword arguments and remove
        # the filter argument if it wasn't passed, otherwise Nuke chokes.
        kwargs = {
            'filter': filter,
            'group': group,
            'recurseGroups': recurseGroups
        }

        # Remove empty arguments
        if not filter:
            del kwargs['filter']

        return nuke.allNodes(**kwargs)

 

and then use the updated snippet :


[a[‘which’].fromScript(allNodes(‘Switch’, recurseGroups=True)[0][‘which’].toScript()) for a in allNodes(‘Switch’, recurseGroups=True)]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Skip to toolbar