From: Carl Banks on
On Apr 20, 1:13 am, Dave Angel <da...(a)ieee.org> wrote:
> Menghan Zheng wrote:
> > Hello!
>
> > Is it assured the following statement is always True?
> > If it is always True, in which version, python2.x or python3.x?
>
> >>>> a = dict()
>
> > ...
>
> >>>> assert(a.values == [a[k] for k in a.keys()])
>
> > --> ?
>
> > Menghan Zheng
>
> No, it's never true.  The assert statement has no return value, neither
> True nor False.
>
> But probably you're asking whether the assert statement will succeed
> quietly.  Again, the answer is no.  The first part of the expression is
> a built-in method, and the second part is a (possibly-empty) list.  So
> it'll always throw an AssertionError.
>
> But probably you've got a typo, and meant to include the parentheses:
>
>    assert(a.values() == [a[k] for k in a.keys()])
>
> That, I believe, is guaranteed to not fire the assertion in 2.6.

Aye.

And in checking a corner case of this I discovered that in (C)Python
it's not possible to define an object that reliably does not equal
itself, because list (at least) is optimized to check identity first.

a = float('nan')
a == a # returns False
[a] == [a] # returns True

Considering that it's rare for an object to not equal itself and much
rarer for this behavior to be useful, and considering the potential
performance gains, it's probably a good trade off, but it's something
to be aware of.


Carl Banks