I am using the following "assert" to validate the argument value in a function I have a function "test" that takes a boolean input "arg1" that can be None, True or False. Is this ok to make sure "arg1" is only one of those possible values?
def test(arg1=None):
assert arg1 in set([None, True, False]), "Not a valid input"
...
My friend tells me the following:
Can't do this. You have to compare True, False, and None as identities (is not =). Doing an in is equivalent to multiple ='s. You have to maintain separate is's.
Is that correct?
Your friend is correct in the case of None
; you should always use identity to test for it unless you're okay with just "noneness" (which you almost never are).
As for True
or False
, you need to examine whether you need the exact values or if just the truthiness is required. If the former then you can use in
to test for them, but if the latter then you shouldn't test at all and just pass the argument to bool()
when you use it in a boolean context.
But there is another problem in your code that both of you have missed:
Assertions should not be used for decision making.
Assertions should be used when actions would have a deleterious effect on the system, not for just validating input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With