Programming, Python

Keyword arguments and merging dictionaries

For instance, Python’s open function opens a file. It takes one, two or three parameters. If you had three files to open you could do it like this:

fileopts = (('junk.output', 'wt'),
            ('buffered.binary.junk', 'wb', 1024),
            ('append text', 'at+'))
files = []
for params in fileopts:
  files.append(open(*params))

A tuple of tuples carried a variable number of arguments for the file function. *params looked the same to the code behind the file function as the more normal approach of passing individual parameters.

Keyword arguments are even nicer. The first three parameters for the open function are called file, mode, and buffering (and there are more, too, such as encoding).

**kwargs (or **whatever) eats all the extra parameters given names by the caller. If a function declares **kwargs in its parameter list, then it sees a dictionary called kwargs. The keys in that dictionary are the names the caller provided, the values are what’s passed.

Here’s a quick example:

def x(**kwargs)

If I call that as x(firstbase = ‘who’, secondbase = ‘what’, thirdbase = ‘I don\’t know’), then x sees that as a dictionary called kwargs in this form:

kwargs = {'firstbase':'who',
          'secondbase':'what',
          'thirdbase':'I don\'t know'}

*args appears as a tuple, **kwargs appears as a dictionary.