Search code examples
pythonnuke

Refactoring code duplication inside function


I want to refactor the assign_hotkey function, because I do not like the duplicated code in the if-statement.

The code:

n_path_i = 0
c_node_i = 1
h_key_i = 2

hotkeys = [
        ['Filter/Blur', 'Blur, size 20 label "hello world"', 'A'],
        ['Draw/LightWrap', 'LightWrap', 'B'],
        ['Draw/Grain', 'Grain2', 'X']
        ]

def assign_hotkey(n_path, c_node, h_key):
    c_node_splitted = c_node.split(',')
    if len(c_node_splitted) > 1:
        menu.addCommand(n_path, 
                        lambda: nuke.createNode(*c_node_splitted),
                        h_key)
    else:
        menu.addCommand(n_path, 
                        lambda: nuke.createNode(c_node),
                        h_key)

for i in hotkeys:
    assign_hotkey(i[n_path_i], i[c_node_i], i[h_key_i])

Solution

  • Since you are unpacking the list you get from splitting c_node when you pass it to nuke.createNode, there is no reason to make a special case at all for the length of the list being 1.

    You can change:

    if len(c_node_splitted) > 1:
        menu.addCommand(n_path, 
                        lambda: nuke.createNode(*c_node_splitted),
                        h_key)
    else:
        menu.addCommand(n_path, 
                        lambda: nuke.createNode(c_node),
                        h_key)
    

    to:

    menu.addCommand(n_path, 
                    lambda: nuke.createNode(*c_node_splitted),
                    h_key)