Zak Ray Sick
Zak Ray Sick

Reputation: 95

Function with varying number of outputs

I am trying to build a python function that loads saved models specified by the user. I would like to design the function so that the user can provide any number of models. As a result, the number of outputs could vary.

A user might use the function in the following way.

model1, model2 = getmodel(model1,model2)

model1, model2, model3 = getmodel(model1,model2,model3)

So far I haven't made it very far.

def getmodel(*models):

    pass

How would I setup my function achieve what I am looking for ? Within the function definition, there is another function "load_function" that I can use to load any individual model.

Upvotes: 0

Views: 86

Answers (4)

rkouye
rkouye

Reputation: 533

def load_model(model):
  return "loaded : "+model # Replace by actual logic

def load_models(*models):
    result = tuple( load_model(model) for model in models)
    if len(result) == 1:
      return result[0]
    return result

modelA = load_models("modelA") or load_model("modelA")

modelB, modelC = load_models("modelB", "modelC")

print(modelA,modelB,modelC)

With these two functions, you can handle any use cases and it will be convenient for your users. To return multiple values in python you can return a tuple or a list, that the user can unpack.

Upvotes: 0

Maxime LD
Maxime LD

Reputation: 13

You could use a tuple or a list containing a varying number of models.

Something like :

model1, model2 = getmodel((model1,model2))

And :

def getmodel(models):
    loaded_models = []
    for model in models:
        loaded_models.append(model_loading_function(model))
    return loaded_models

Upvotes: 1

Tarifazo
Tarifazo

Reputation: 4343

Just use map:

model1, model2, model3 = map(your_load_model_function, (model1, model2, model3))

Upvotes: 0

Luke B
Luke B

Reputation: 2121

def getmodel(*models):
    all_models=[]
    for model in models:
            all_models.append(load_function(model))
    return all_models

Using a star on your argument allows it to accept any number of inputs, converting them to a list.

When a list is returned, python will automatically unpack the values into separate variables if you try to set them all equal to one list.

a, b, c = ["apple", "bee", "cat"]

This way, although the getmodel function returns a list, it will be assigned to the individual variables.

Upvotes: 0

Related Questions