copysort patch, was RE: [Python-Dev] inline sort option
Guido van Rossum
guido at python.org
Tue Oct 28 12:42:16 EST 2003
> Hmmm... maybe one COULD make a custom descriptor that does support
> both usages... and maybe it IS worth making the .sorted (or whatever name)
> entry a case of exactly such a subtle custom descriptor...
Thanks for the idea, I can use this as a perverted example in my talk
at Stanford tomorrow. Here it is:
import new
def curry(f, x, cls=None):
return new.instancemethod(f, x)
class MagicDescriptor(object):
def __init__(self, classmeth, instmeth):
self.classmeth = classmeth
self.instmeth = instmeth
def __get__(self, obj, cls):
if obj is None:
return curry(self.classmeth, cls)
else:
return curry(self.instmeth, obj)
class MagicList(list):
def _classcopy(cls, lst):
obj = cls(lst)
obj.sort()
return obj
def _instcopy(self):
obj = self.__class__(self)
obj.sort()
return obj
sorted = MagicDescriptor(_classcopy, _instcopy)
class SubClass(MagicList):
def __str__(self):
return "SubClass(%s)" % str(list(self))
unsorted = (1, 10, 2)
print MagicList.sorted(unsorted)
print MagicList(unsorted).sorted()
print SubClass.sorted(unsorted)
print SubClass(unsorted).sorted()
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list