Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a correct way to check if an argument value is part of a defined range of values?

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?

like image 819
Diego Avatar asked Feb 07 '23 23:02

Diego


1 Answers

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.

like image 189
Ignacio Vazquez-Abrams Avatar answered May 14 '23 00:05

Ignacio Vazquez-Abrams