comparison with None
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Thu Apr 19 10:31:59 EDT 2007
On Wed, 18 Apr 2007 15:19:26 -0700, Steven Howe wrote:
> I've read and found that 'None' comparisons is not always a good idea.
You're probably thinking of testing against None with equality:
if x == None: do_something()
That can go wrong if x is a class that has an overly-broad concept of
equality, e.g.:
class FalseKlass:
def __eq__(self, other):
# equal to anything that is False
return not other
> Better to:
> from types import NoneType
>
> x = None
> if type( x ) == NoneType:
> # true
> < code >
> else:
> # false; do something else.
> < more code >
Not necessary. Since None is a guaranteed singleton, the only test you
need to make is "if x is None: ...".
But if you wanted to do extra work unnecessarily, a less unnecessary
amount of extra work would be:
if type(x) == type(None): ...
You don't need to look up the type of None in the types module when you
can easily get it from the type() function.
--
Steven.
More information about the Python-list
mailing list