Question

Does anyone have ideas about the codes below?

>>> memoryview("abc") < memoryview("bca")
True
>>> memoryview("abc") > memoryview("bca")
True
>>> memoryview("abc") = memoryview("bca")
False

How can I compare the string of memoryview objects without using tobytes to get a copy of the string?

Was it helpful?

Solution

memoryview() objects do not define any ordering, it's __lt__ and __gt__ methods return the NotImplemented singleton indicating that they don't support ordering:

>>> memoryview("abc").__lt__(memoryview('bca'))
NotImplemented
>>> memoryview("abc").__gt__(memoryview('bca'))
NotImplemented

Thus, Python 2 sorts these using an internal, consistent ordering. In Python 3 a TypeError will be raised instead when you attempt to use the < and > operators.

In python 2, when objects don't support ordering, they are instead ordered by their memory address (for the object itself, not the 'memory' the memoryview is pointing at); see Custom class ordering: no error thrown, what is Python testing for? for more details on what happens.

Only equality and inequality testing is supported:

>>> memoryview("abc").__eq__(memoryview('bca'))
False
>>> memoryview("abc").__eq__(memoryview('abc'))
True
>>> memoryview("abc").__ne__(memoryview('abc'))
False
>>> memoryview("abc").__ne__(memoryview('bca'))
True

Your only options are to use .tobytes() or .tolist().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top