Multiple Return Values from a Function
The Problem
In some cases, you might have a Python function that returns multiple values.
This is very common when you're trying to balance several different inputs or outputs.
The difficulty is that each output can only return a single value - so how do you make sure that you get all of the values returned by a function, and only call it once?
The Solution
The trick is that calculations - because they aren't published - can have any value. So you can use them to store Python arrays, tuples, or objects.
Let's say we have a machine with four motors. You're trying to balance the workload between each of them, and have created a Python function to do that.
def MyMotorBalancer(a,b,c,d,e,f,g): motor1 = 0 motor2 = 0 motor3 = 0 motor4 = 0 #Insert actual work here return [motor1,motor2,motor3,motor4]
This function takes a number of inputs, and returns four outputs.
You might be tempted to make four individual outputs, each of which call the function.
mod.AddOutput("Motor1 Out",lambda: MyMotorBalancer(...)[0],[...]) mod.AddOutput("Motor2 Out",lambda: MyMotorBalancer(...)[1],[...]) mod.AddOutput("Motor3 Out",lambda: MyMotorBalancer(...)[2],[...]) mod.AddOutput("Motor4 Out",lambda: MyMotorBalancer(...)[3],[...])
….but that's really inefficient. You don't want to call the MyMotorBalancer four times if the answer is going to be the same, particularly if the function takes some time to run.
By adding a calculation step, you can make sure you only call the function once.
Balance = mod.AddCalc("Motor Balance", lambda: MyMotorBalancer(...),[]) mod.AddOutput("Motor1 Out",lambda: Balance[0],[Balance]) mod.AddOutput("Motor2 Out",lambda: Balance[1],[Balance]) mod.AddOutput("Motor3 Out",lambda: Balance[2],[Balance]) mod.AddOutput("Motor4 Out",lambda: Balance[3],[Balance])