Parameters to Python Dictionary Code

Last updated on: 24 January, 2024

Summary: A short instruction on how to generate Python code that supplies dictionary of selected operator’s parameters and their values.

Today I had to create an HDA which was required to contain several presets, but which would also had to be shipped as a single .hda file (so say goodbye to extra .idx files).

I decided to put presets into dictionary variables inside the PythonModule, and simply use a callback function invoked from Ordered Menu to automatically set all parameters. Now, while I’m sure the end user will find the menu-based preset selection quite convenient, I found the process of creating presets this way to be quite a chore. And you can imagine why.

First of all, I had to create a separate dictionary for each preset. Then, I had to tweak the parameters according to certain supplied specifications, and see how the result looks like in the viewport. After this, I had to write down values of each parameter and paste them into the dictionary. The HDA has plenty of parameters, so after several minutes I concluded that the process is not only incredibly prone to human error, but also repulsively tedious.

As a remedy to this awful task, I wrote a simple script that in large degree automates this process by returning a Python dictionary code ready to be pasted into my HDA’s PythonModule. The program operates on the first item of the array of selected operators, but it can be easily modified to work on multiple selection of nodes.

Here’s the code:

node = hou.selectedNodes()[0]
print('preset_name = {')
for parm in node.parms():
    parm_type = parm.parmTemplate().type()
    ignored = (
        hou.parmTemplateType.Menu,
        hou.parmTemplateType.FolderSet,
    )
    strings = (
        hou.parmTemplateType.String,
    )
    if parm_type in ignored:
        continue
    if parm_type in strings:
        print(f"\t'{parm.name()}': '{parm.eval()}',")
    else:
        print(f"\t'{parm.name()}': {parm.eval()},")
print('}')

The ignored tuple holds a list of parameter template types that the script will ignore. In my case it was the ordered menu, which holds the presets, and folders which are used to hierarchize asset’s parameters. The strings tuple stores types that are output as strings and as such need to be enclosed in quotation marks.