<var> is None vs. <var> == None
Jason Scheirer
jason.scheirer at gmail.com
Fri Jan 23 16:40:51 EST 2009
On Jan 23, 12:48 pm, Roger <rdcol... at gmail.com> wrote:
> > And, just for completeness, the "is" test is canonical precisely because
> > the interpreter guarantees there is only ever one object of type None,
> > so an identity test is always appropriate. Even the copy module doesn't
> > create copies ...
>
> Does the interpreter guarantee the same for False and True bools?
Yes. I know that there are the PyObject* structs defined for you
Py_True, Py_False and Py_None in the C level. Confusingly enough, the
integers -5 through 257 are also singletons where the is test will
work, but any int out of that range will not.
>>> def copy_id(x):
... id1, id2 = id(x), id(copy.deepcopy(x))
... print "Equal: %x %s %x" % (id1, ('==' if id1 == id2 else '!
='), id2)
...
...
>>> copy_id(a())
Equal: a8fc90 != f32370
>>> copy_id(1)
Equal: 9559c8 == 9559c8
>>> copy_id(None)
Equal: 1e1da9f0 == 1e1da9f0
>>> copy_id(True)
Equal: 1e1c5ec4 == 1e1c5ec4
>>> copy_id(False)
Equal: 1e1c5eb8 == 1e1c5eb8
>>> copy_id("Hello")
Equal: 1058840 == 1058840
>>> copy_id([])
Equal: 1067030 != 10673f0
... large equal integers are not identical in memory location ...
In [34]: x = 19591
In [35]: y = 19590+1
In [36]: id(x), id(y)
Out[36]: (17937008, 17936588)
... but small ones are ...
In [40]: x = 2
In [41]: y = 1+1
In [42]: id(x), id(y)
Out[42]: (9787836, 9787836)
More information about the Python-list
mailing list