List comprehension for testing **params
Terry Reedy
tjreedy at udel.edu
Sun Nov 11 18:37:05 EST 2012
On 11/11/2012 5:56 PM, Ian Kelly wrote:
> 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):
or if you want them to be identified by keyword only (since 7 positional
args is a bit much)
def __init__(self, smtp, login, *, subject, from, to, msg):
(I forget when this feature was added)
> # ...
>
> And then Python will do all the work of requiring them to be present for you.
>
--
Terry Jan Reedy
More information about the Python-list
mailing list