List comprehension for testing **params

Ian Kelly ian.g.kelly at gmail.com
Sun Nov 11 17:56:52 EST 2012


On Sun, Nov 11, 2012 at 3:24 PM, Cantabile <cantabile.03 at wanadoo.fr> wrote:
> I'd like to do something like that instead of the 'for' loop in __init__:
>
> assert[key for key in required if key in params.keys()]

A list evaluates as true if it is not empty.  As long as at least one
of the required parameters is present, the list will not be empty and
will evaluate as true, and the assertion will pass.  Try this instead:

assert all(key in params.keys() for key in required)

By the way, using assertions for input checking is generally not
considered good practice.  As soon as Python is invoked with the -O
option, your input testing is tossed out the window.  Assertions are
good to use for internal logic testing, to avoid unexpected state.
For input checking, use an explicit if test and exception:

if any(key not in params.keys() for key in required):
    raise ValueError("Missing required keyword argument")

Additionally, if the arguments are required, then they probably have
no business being wrapped up in **params in the first place.  Why not
just define your method like:

def __init__(self, smtp, login, subject, from, to, msg):
    # ...

And then Python will do all the work of requiring them to be present for you.



More information about the Python-list mailing list