I failed to mention that what Drew and I both stated are opposite sides
of the same coin.
When explicitly looking for None, use 'is'.
When comparing the "truthiness" of an object, "if <object>" works best
(e.g. for checking lists, strings, etc. to ensure they're not empty and
also not None - this is also in PEP 8).
It all depends on the context of the comparison in question.
- Keith
On 07/19/10 12:10 PM, Keith Mitchell wrote:
When comparing to None (and other singletons), using 'is' is preferred
by PEP 8:
Programming Recommendations
[...]
- Comparisons to singletons like None should always be done with
'is' or 'is not', never the equality operators.
Also, beware of writing "if x" when you really mean "if x is not None"
-- e.g. when testing whether a variable or argument that defaults to
None was set to some other value. The other value might have a type
(such as a container) that could be false in a boolean context!
- Keith
On 07/19/10 12:05 PM, Drew Fisher wrote:
Dermot:
Take a look here:
http://docs.python.org/release/2.5.2/lib/truth.html
None evaluates to false (the truth value) the same as 0, False (the
boolean), [] , (), {}, etc.
Using 'is' can be very dangerous. 'is' is used to test object
identity. It checks to make sure the two varaibles are the same
object and not just equal.
Example:
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> 257 is 257
True
You CAN use 'is' with None because None is actually a class (run
dir(None) to see) but if we're simply testing for true/false (truth
values), it's easier to be consistent and simply use "if not
<variable>". This way if <variable1> is None/Not None and
<variable2> is True/False and <variable3> is 0/!0, a simple truth
value test can all be written the same way.
I hope this makes sense.
-Drew
Drew,
Just picking up on one item:
On 07/19/10 18:40, Drew Fisher wrote:
- tests for None can be done with
if not variable:
instead of
if variable == None:
and likewise for not None.
I have always heard that the recommended way to do this is:
if variable is None:
(or if variable is not None:)
Is your suggestion:
if not variable:
the preferred PEP8 way? Wouldn't that also evaluate to true if
variable
had a value of False, rather than None?
- Dermot
_______________________________________________
caiman-discuss mailing list
[email protected]
http://mail.opensolaris.org/mailman/listinfo/caiman-discuss
_______________________________________________
caiman-discuss mailing list
[email protected]
http://mail.opensolaris.org/mailman/listinfo/caiman-discuss
_______________________________________________
caiman-discuss mailing list
[email protected]
http://mail.opensolaris.org/mailman/listinfo/caiman-discuss