How to acces *args

I have a function with a lot of parameters and sometimes one more
all what I find on the net the parameters are interated in a loop,

def create_combo(l_name, l_text, row,l_col, c_name, c_col, c_size, c_list, *args):
	l_name=ttk.Label(root,text=l_text)
	l_name.grid(row=row,column=l_col,padx=2,pady=2)
	c_name=ttk.Combobox(root,values=c_list, width=c_size)
	c_name.current(8)
	c_name.grid(row=row,column=c_col,padx=2,pady=2)

sw_typ_list=("pushButton","revPushButton","nSwitch","uSwitch","eSwitch","pToggleSwitch")
create_combo("l_typT1", "Typ SW T1",1,0,"c_typT1",1,12,sw_typ_list,0)

the last parameter should be a default value for the combox, but sometimes I want omit it. I generate the combobox with a function as I have al lot of comboxes in my form. I know the names are bit krypto for peoble do not know the form is for, it is to create a 150 byte config file, where each byte has its own sence

Any hint ?

Regards
Rainer

Rather than using *args for this use case you should use a keyword argument with a default:

def create_combo(l_name, l_text, row,l_col, c_name, c_col, c_size, c_list, default=None):

By doing that you have a variable name to reference and a default value assigned to it. The calling function does not need to include it, since it has a default value.

Thank you for quick help, that works,
Regards
Rainer

1 Like

Hello,

just an fyi, *args is useful if you’re going to be passing in arguments one right after another, and when the quantity is unknown (number of arguments passed in can vary). In your case, since you only have one argument that may or may not be passed in, then the method as @brass75 described works just fine.

Here is a simple test script to test the different ways *args is interpreted when passing in individual values versus values being passed in a list (or tuple).

def misc_args(a_list, *args):

    print(a_list)

    print(args)

some_list = [1,2,3,4,5]        # Entered via parameter 'some_list'
another_list = [6,7,8,9,10]

This:

misc_args(some_list, 33,11,22)  # Entering arguments right after another

Produces this:

[1, 2, 3, 4, 5]
(33, 11, 22)  # easy to iter over values

However, if you pass in a list in as an *args, then it does not work as desired because then it is interpreted as the first element in a tuple:

This:

misc_args(some_list, another_list )  # Entering arguments as a 'list'

Produces the following:

[1, 2, 3, 4, 5]
([6, 7, 8, 9, 10],)  # Not straightforward to iter over values 

Hope this helps with answering the question posed by the title of this post.

1 Like