The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Is This A Correct Way To Check If An Argument Value Is Part Of A Defined Range Of Values?
00:47 Accepted Answer Score 4
01:26 Answer 2 Score 4
01:43 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.