Nudin
Nudin

Reputation: 371

Python: calling a function with varying number of arguments

I want to write a function witch converts a dictionary into a Gtk-ListStore, where the Gtklist-store should have n columns, the first to to be key and value of the dictionary and the rest to be empty strings. N should be given by the user.

The constructor of ListStore demands for the types of the columns. How to specify them in the right number?

Here is the function supporting only 2 or 3 columns to demonstrate the problem:

def dict2ListStore(dic, size=2):
  if size == 2:
    liststore = Gtk.ListStore(str, str)
    for i in dic.items():
       liststore.append(i)
    return liststore
  elif size == 3:
    liststore = Gtk.ListStore(str, str, str)
    for i in dic.items():
       l = list(i)
       l.append("")
       liststore.append(l)
    return liststore
  else:
    print("Error!")
    return

Upvotes: 1

Views: 4730

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279295

liststore = Gtk.ListStore(*([str] * size))

[str] * size is a list with size repetitions of str.

func(*args) is the way to pass the values contained in a sequence args, as multiple arguments.

Upvotes: 3

Related Questions