[Python-Dev] Fwd: Python 3.3 can't sort memoryviews as they're unorderable (original) (raw)

Steven D'Aprano steve at pearwood.info
Thu Oct 25 18🔞47 CEST 2012


On 26/10/12 02:57, Mark Lawrence complained that he can't subclass memoryviews:

I'm guessing that I've missed something that's blatantly obvious to everybody except myself. I can't find a rationale anywhere as to why I can't subclass memoryviews for my code, so I can't work around what I perceive as a glaring deficiency. Is it a case whereby even consenting adults aren't allowed?

This strikes me as so different to the Python that I've been using for the last 10 years that it stood out, at least to me, like a sore thumb. Perhaps I need yet another visit to the opticians?

Possibly. There are many things that you can't subclass in Python.

NoneType NotImplementedType Ellipsis functions slices frames tracebacks

and probably others.

As annoying as it is when you run into something like this, it's hardly without precedent. Hell, for about half of Python's existence, you couldn't even subtype basic types like int, str and list!

Subclassing is not the only way to add functionality to a class. While it is much less convenient with new-style classes than classic classes, why don't you try delegation? Actually, since the problem you are trying to solve is to sort a list of memoryviews, you don't even need delegation. You just need a dirt-simple key function.

py> mv = memoryview py> x = list(map(mv, (b'xyz', b'abc', b'pqr'))) py> x.sort(key=lambda x: x.obj) py> [a.obj for a in x] [b'abc', b'pqr', b'xyz']

What was the problem again?

:)

-- Steven



More information about the Python-Dev mailing list