These 3 lines could be simplified to:  node_ids = set(port.node_id for port in ports)