Using custom comparasion function in sequence.sort
I'd like to use a custom comparasion function in a PythonScript to sort certain objects, using the sequence.sort utility function. In the doc-string for sort in sequence/SortEx.py, there is a line about custom function: - "xxx" -- a user-defined comparison function So I defined a comparasion function in the PythonScript and passed its name to sort. However, when the script is called, I got the error: * Module DocumentTemplate.sequence.SortEx, line 66, in sort * Module DocumentTemplate.sequence.SortEx, line 175, in make_sortfunctions AttributeError: 'NoneType' object has no attribute 'getitem' A closer look at make_sortfunctions shows that it tries to find the custom comparasion in the name space '_', which is default to None in sort(). So it seems I need only supply the correct name space as the third, undocumented parameter to sequence.sort for it to find my comparasion function. I tried to use globals() but this seems to be unavailable in a PythonScript. So the question is, how to pass the correct name space containing my comparasion function to the sort() function? My PythonScript code segment looks like below: results = ... def my_cmp(x, y): return cmp(x,y) sort_on = (('property', 'my_cmp', 'asc'),) return sequence.sort(results, sort_on) Thanks for advices. Best Regards, Hong Yuan
Hong Yaun wrote at 2005-2-14 13:11 +0800:
... A closer look at make_sortfunctions shows that it tries to find the custom comparasion in the name space '_', which is default to None in sort(). So it seems I need only supply the correct name space as the third, undocumented parameter to sequence.sort for it to find my comparasion function.
Unfortunately, this is not so easy, because this argument must behave like a DTML namespace... Especially, it must have a "getitem" method with 2 positional arguments. Maybe, you can bind the "namespace" in your Python script. When called from a DTML object, this namespace is bound to the DTML namespace, when called from a PageTemplate, this namespace contains the variables defined at this point of the PageTemplate. But apparently, "sequence.sort" was not designed to be used from something differently than DTML (which is a pity). -- Dieter
participants (2)
-
Dieter Maurer -
Hong Yaun