I can manually hide unused node sockets by pressing Ctrl H, but I wanted to know how to hide an unused node socket using a script I saw a previously asked question about this topic - How can I hide unused node sockets? in the answers, VRm answered that Hide attribute can do this but hide attribute can just collapse the node itself like when we press 'H.
1 Answer
$\begingroup$
$\endgroup$
You can either call hide.socket_toggle() operator on all nodes in selection or hide each socket one by one using NodeSocket.hide property. Following demo is based on Operator Node template:
import bpy
def main(operator, context):
node_selected = context.selected_nodes
if node_selected:
bpy.ops.node.hide_socket_toggle()
else:
operator.report({'ERROR'}, "Nothing selected")
return
class NODE_OT_Operator(bpy.types.Operator):
"""Tooltip"""
bl_idname = "node.simple_operator"
bl_label = "Hide Node Sockets Operator"
@classmethod
def poll(cls, context):
space = context.space_data
return space.type == 'NODE_EDITOR'
def execute(self, context):
main(self, context)
return {'FINISHED'}
def register():
bpy.utils.register_class(NODE_OT_Operator)
def unregister():
bpy.utils.unregister_class(NODE_OT_Operator)
if __name__ == "__main__":
register()

Result of calling the operator on all selected nodes in the shader editor

Result of calling the operator on all selected nodes in the compositor
Demo on how to hide the alpha sockets of Render Layer and Composite node using the console:
>>> rl_node = C.scene.node_tree.nodes.get('Render Layers')
>>> alpha_socket = rl_node.outputs.get("Alpha")
>>> alpha_socket.hide = True
>>>
>>> comp_node = C.scene.node_tree.nodes.get('Composite')
>>> alpha_socket = comp_node.inputs.get("Alpha")
>>> alpha_socket.hide = True

