Home > Software design >  Passing many variables as one variable in python
Passing many variables as one variable in python

Time:12-02

I have a list of variables that I want to send to my function. (so the function works based on the values on those variables).

One way is to pass each variable separately in the function like this:

def my_function(var1, var2, var3, var4, ..., varn):
   output = var1   var2   var3   var4   ....   varn

However, I wonder if I can write such a thing:

def my_function(parameters):
    output = parameters.var1   parameters.var2   ...   parameters.varn

That is, somehow is there any way to wrap all variables in one variable, and then call them like this?

I know the above python codes are not correct, I just want to express my question.

Thanks in advance

CodePudding user response:

There are many options. You have to determine which way fits your case.

Option 1. Getting multiple arguments by a single asterisk

def my_function(*args):
    output = sum(args)

    # SAME WITH
    # output = args[0]   args[1]   ...   args[n]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function(10, 20, 10, 50)

Option 2. Getting keyword arguments by double asterisk

def my_function(**kwargs):
    output = sum(kwargs.values())
    
    # SAME WITH
    # output = kwargs["var0"]   kwargs["var1"]   ...   kwargs["varn"]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function(var0=10, var1=20, var2=15)

Option 3. Getting an argument as a list

def my_function(list_arg):
    output = sum(list_arg)

    # SAME WITH
    # output = list_arg[0]   list_arg[1]   ...   list_arg[n]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function([1, 10, 3, -10])

Option 4. Getting an argument as a dictionary

def my_function(dict_arg):
    output = sum(dict_arg.values())

    # SAME WITH
    # output = kwargs["var0"]   kwargs["var1"]   ...   kwargs["varn"]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function({"var0":5, "var1":10, "var2":3})
  • Related