List comprehension for testing **params

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Mon Nov 12 11:48:06 CET 2012


Am 11.11.2012 23:24, schrieb Cantabile:
> I'm writing a small mail library for my own use, and at the time I'm
> testing parameters like this:

Let's ignore the facts that there is an existing mail library, that you 
should use real parameters if they are required and that exit() is 
completely inappropriate. Others explained why sufficiently.

[slightly shortened]
> def function(**params)
>     required = ['Subject', 'From', 'To', 'msg']
>     for i in required:
>         if not i in params.keys():
>             print "Error, \'%s\' argument is missing" %i

Let's start with the last line: If you use "Error, missing {!r} 
argument".format(i), you get the quotes automatically, plus possibly 
escaped unicode characters and newlines, although it's not necessary. 
Also, I would "from __future__ import print_function" in any new code, 
to ease upgrading to Python 3.

Now, concerning the test whether the required parameters are passed to 
the function, you can use "if i in params", which is slightly shorter 
and IMHO similarly expressive. Also, it doesn't repeatedly create a 
list, checks for a single element inside that list and then throws the 
list away again. Further, you don't even need a list for the parameters, 
since order doesn't matter and duplicates shouldn't exist, so I would 
use a set instead:

   required = {'Subject', 'From', 'To', 'msg'}

The advantage is slightly faster lookup (completely irrelevant for this 
small number of elements) but also that it makes the intention a bit 
clearer to people that know what a set is.

In a second step, you compute the intersection between the set of 
required arguments and the set of supplied arguments and verify that all 
are present:

    if required.intersection(params.keys()) != required:
        missing = required - set(params.keys())
        raise Exception("missing arguments {}".format(
                        ', '.join(missing)))


Happy hacking!

Uli



More information about the Python-list mailing list