[Zope] Sorting Zope objects in python scripts

Oliver Bleutgen myzope@gmx.net
Tue, 04 Dec 2001 18:10:11 +0100


complaw@hal-pc.org wrote:

> If one were to write...
> 
> myList = []
> for obj in context.objectValues(['Folder', 'DTML Document']):
>   if obj.instance_type = 'Desired Class':
>     myList.append(obj)
> 
> .. then I would want to sort the various objects.  The question is, how do I do
> that?
> 
> I could do...
> 
> myList.sort()
> 
> .. but that doesn't give me a way to control on which property the sort is
> done.  You could use a sort function, such as...
> 
> def compare_integers(first=0, second=0):
>   if first > second:
>     return 1
>   else:
>     if first == second:
>       return 0
>     else:
>       return -1
> 
> .. and this leads to the part that I just don't grok.  How do I specify a
> particular property within an object (such as element_number) as the parameter
> to be used for the comparison?  Do I just...
> 
> myList.sort(compare_integers)
> 
> ??
> 
> Can anyone give me a quick hint?  The python documentation is a little short in
> this area.


Hi Ron,
it's not clear to me if you want to dynamically give the property on 
which to sort or if this can be static. I don't know how to do the first 
in an elegant way, but here is the second:

def compare_integers(a,b):
     return cmp(a.element_number, b.element_number)

myList.sort(compare_integers)

i.e. you handle the objects to your custom compare method and it gets 
the attribute it wants to compare from the objects.

Oh, and if the object itself knows on what it wants to be sorted, you 
could use

def compare_integers(a,b):
     return cmp(getattr(a,a.what_to_sort), getattr(b,b.what_to_sort))

i.e. a.what_to_sort would be a string property holding the name of the 
property on which a and b want to be sorted. You could also use some 
global variable which you set in your script, and your compare method 
would retrive it.



HTH,
oliver