Differencebetween "Is None" and "== None"

What is the difference between is None and == None

The answer is explained here.

To quote:

A class is free to implement
comparison any way it chooses, and it
can choose to make comparison against
None mean something (which actually
makes sense; if someone told you to
implement the None object from
scratch, how else would you get it to
compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.

Python None comparison: should I use is or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
def __eq__(self,other):
return not other

thing = Negator()
print thing == None #True
print thing is None #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:] # This is True since the lists are "equivalent"
lst is lst[:] # This is False since they're actually different objects

what is difference between [None] and [] in python?

[] is an empty list

[None] is a list with one element. That one element is None

is checks for reference equality. If both objects refer to the same object by reference then is will return true.

a = []
b = a
a is [] #false
a is b #true

Boolean identity == True vs is True

If you want to determine whether a value is exactly True (not just a true-like value), is there any reason to use if foo == True rather than if foo is True?

If you want to make sure that foo really is a boolean and of value True, use the is operator.

Otherwise, if the type of foo implements its own __eq__() that returns a true-ish value when comparing to True, you might end up with an unexpected result.

As a rule of thumb, you should always use is with the built-in constants True, False and None.

Does this vary between implementations such as CPython (2.x and 3.x), Jython, PyPy, etc.?

In theory, is will be faster than == since the latter must honor types' custom __eq__ implementations, while is can directly compare object identities (e.g., memory addresses).

I don't know the source code of the various Python implementations by heart, but I assume that most of them can optimize that by using some internal flags for the existence of magic methods, so I suspect that you won't notice the speed difference in practice.

SQLAlchemy - Accounting for the None Case in a nested OR Relationship

Use '== None' instead of 'is None'

conn.query(Identifier.Key)\
.filter(and_(Identifier.DatetimeStart <= datetime.datetime.now(),
or_(Identifier.DatetimeEnd <= datetime.datetime.now(), Identifier.DatetimeEnd == None)))\
.all()

SELECT identifier.identifier_id AS identifier_identifier_id
FROM identifier
WHERE identifier.datetime_start <= ? AND (identifier.datetime_end <= ? OR identifier.datetime_end IS NULL)

Difference between None and no value

It's just a documentation thing, there is no such concept in Python itself.

Take into account that None in itself is also a valid object. Sometimes you want to accept None as a valid value for an argument, so you can't use that as the default value for an optional parameter. You wouldn't be able to distinguish between the default None and someone passing in None explicitly, since it's a singleton!

If I needed to define such a function, I'd use a different singleton sentinel. You can create one from just about anything, but simplest is to use an object() instance:

_sentinel = object()

def foo(bar, baz=_sentinel):
if baz is not _sentinel:
# baz has a defined value, because it is
# not a reference to the sentinel

And perhaps I'd also use <no value> in the documentation to indicate that baz is optional. It all depends on the local conventions. The Python documentation itself uses [...] around optional arguments, for example.

numpy.amin() is actually a proxy function; it delegates the actual work either to numpy.minimum() (via ufunc.reduce(), or, if the first argument is a subclass that implements an amin() method, to that method of the subclass. Because the latter should be able to set their own defaults, using a sentinel lets the numpy.amin() implementation pass on only those keyword arguments that actually were given an explicit value, without dictating what kind of sentinel the subclass .amin() implementations should use or what types they accept.

The Numpy project actually created their own singleton class to act as a sentinel so they could give the object a helpful repr() output:

>>> from numpy._globals import _NoValue
>>> _NoValue
<no value>
>>> type(_NoValue)
<class 'numpy._globals._NoValueType'>

Finally, None should not be compared with null or nullptr. None is a singleton object, something to reference instead of another object. null and nullptr are used to signal the absence of a reference, and can be passed around like other scalar values. You can't do this in Python, where everything is a valid reference to an object. (At most, you get a NameError or UnboundLocal exception if you tried to use a name that hasn't been bound to yet in its namespace).

Is there any difference between foo is None and foo == None ?

is always returns True if it compares the same object instance

Whereas == is ultimately determined by the __eq__() method

i.e.


>>> class Foo(object):
def __eq__(self, other):
return True

>>> f = Foo()
>>> f == None
True
>>> f is None
False

Should I compare with None explicitly

It depends on the values your variable may take and the expectations your code has. If your variable may take on other falsey values, then yes, the difference between None and, say, [] may be significant and you need to explicitly check for is None.

But not always. What if your value is a falsey [], and you're writing an if foo: to decide whether you have a value that needs processing? Well, an empty list might not need processing either, since it's empty. So both None and [] can be treated the same. In this case you'd need to explicitly check for is None and and empty list, in which case if foo: already encapsulates both very succinctly.

In your case, if the variable can be either None or a Thread, there's no difference whether you add is not None or not, it will behave identically in both cases. So why make it more verbose than it needs to be?

There's no one rule that fits all situations.

Do the commands x is None and x == None return always the same result if x is immutable?

It has nothing to do with the immutability of x. None is a singleton for which is and == return identical results, unless the type of x defines a weird __eq__ method. The name x is either bound or not bound to the same object as None. If not, the identity check will always be False, regardless of what other type it is. The result of the equality check is up to the type of x, but will be the same as the identity check for most sane classes.

Now the caveat is that while you can't override is, since that's an identity check done by the interpreter, you can override ==. Aside from speed and consistency, here's a toy example showing why x is None is preferable to x == None:

class Test:
def __eq__(self, other):
if other is None:
return True
return self is other
>>> Test() == None
True
>>> None == Test()
True
>>> Test() is None
False
>>> None is Test()
False

The reason that both Test () == None and None == Test() return the same result has to do with how comparisons are evaluated, and the fact that None does not define an explicit __eq__ method. Normally, the interpreter calls type(left).__eq__(left, right) on the operands. If the left operand's type does not define __eq__ or the method returns NotImplemented, it attempts type(right).__eq__(right, left). Only if both fail does it fail over to a built-in identity check. Since None doesn't define an equality check, it will always use the check defined by the other object before failing over to the identity check.

What is the difference between None and False in python 3? (in a boolean sense)

Different values in Python can be described as being "truthy" or "falsy" even if they aren't Boolean values, which means they are interpreted as True or False in a situation that expects a Boolean value (such as an if condition). As defined in the documentation, every value in Python, regardless of type, is interpreted as being True except for the following values (which are interpreted as False):

  • Constants defined to be false: None and False.
  • Zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • Empty sequences and collections: '', (), [], {}, set(), range(0)

To your specific situation, using the if situation, the following statement:

if None:
# some code here

would be functionally identical to:

if False:
# some code here

This is because, as shown in the list above, the value None is automatically converted to False for the purposes of the if condition. This is something referred to as "syntactic sugar", which is a feature of the language that exists to make the developer's life easier.

However, just because None is interpreted as False in this particular scenario, that doesn't mean the two values are equal to each other. This is because False is meant to be part of the True/False pair indicating binary concepts like "yes/no", "on/off", etc. None, on the other hand, represents the concept of nothing. Variables with a value of None means they have no value at all. To compare it to False in the form of a metaphor, False would be like answering somebody by saying "No", where None would be like not answering them at all.

As a more practical example, see the following code snippet:

if None == False:
# code in here would not execute because None is not equal to False


Related Topics



Leave a reply



Submit