The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Question
00:57 Accepted answer (Score 4)
01:45 Answer 2 (Score 4)
02:13 Thank you

--

Full question
https://stackoverflow.com/questions/3732...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27

#avk47



ACCEPTED ANSWER

Score 4


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.




ANSWER 2

Score 4


If you need identity testing, you must use "is." Your friend is correct, as "in" uses equality testing. For example:

a = [0, 1]
False in a
>> True
a[0] is False
>> False

If someone passes in a 0, it will not trigger your assertion. You may not be expecting that.