# -*- coding: iso-8859-1 -*-
#-----------------------------------------------------------------------------
# Modeling Framework: an Object-Relational Bridge for python
#
# Copyright (c) 2001-2004 Sbastien Bigaret <sbigaret@users.sourceforge.net>
# All rights reserved.
#
# This file is part of the Modeling Framework.
#
# This code is distributed under a "3-clause BSD"-style license;
# see the LICENSE file for details.
#-----------------------------------------------------------------------------
"""
Module SortOrdering holds a "command" pattern for sorting objects, and the
appropriate methods for building and using the commands.
A command for sorting is an instance of L{SortOrdering}; it can be built
either directly or with the method L{sortOrderingsWithString}. A command can
be used alone or inserted in a sequence of sorting command; in the later case,
the resulting sorting method simply consists in sorting objects with the first
method in the sequence, than sorting the objects which are equal wrt the first
method using the second one in the sequence, etc.
A command consists in a key and an operator (see below: L{compareAscending},
...); the sorting mechanism uses
L{KeyValueCoding.valueForKeyPath<KeyValueCoding.KeyValueCoding.valueForKeyPath>}
with the command's key to access the values for objects' attributes.
Sorted objects must implement the KeyValueCoding interface's method
L{KeyValueCoding.valueForKeyPath<KeyValueCoding.KeyValueCoding.valueForKeyPath>}):
it is used to access objects' values.
Example of use:
>>> from Modeling.SortOrdering import sortOrderingsWithString, sortedArrayUsingKeyOrderArray
>>> name_age=sortOrderingsWithString('lastName, age desc')
>>> sortedArrayUsingKeyOrderArray(self.authors, name_age)
CVS Information: $Id: SortOrdering.py 932 2004-07-20 06:21:57Z sbigaret $
"""
__version__='$Revision: 932 $'[11:-2]
from interfaces.SortOrdering import SortOrderingInterface
from utils import staticmethod
# Predefined Operators
def compareAscending(value1, value2):
"This operator allows to sort values in ascending order"
if value1 < value2: return -1
elif value1 == value2: return 0
else: return 1
def compareDescending(value1, value2):
"This operator allows to sort values in descending order"
if value1 > value2: return -1
elif value1 == value2: return 0
else: return 1
def compareCaseInsensitiveAscending(value1, value2):
"This operator allows to sort strings in ascending order, case-insensitively"
up1=value1.upper(); up2=value2.upper()
if up1 < up2: return -1
elif up1 == up2: return 0
else: return 1
def compareCaseInsensitiveDescending(value1, value2):
"This operator allows to sort strings in descending order, case-insensitively"
up1=value1.upper(); up2=value2.upper()
if up1 > up2: return -1
elif up1 == up2: return 0
else: return 1
def operatorFromString(str):
"""
Converts a string to the corresponding operator. Recognized strings are:
'asc', 'desc' and their case-insensitive counterparts: 'iasc' and 'idesc'
"""
op=str.lower().strip()
if op == 'asc': return compareAscending
if op == 'iasc': return compareCaseInsensitiveAscending
if op == 'desc': return compareDescending
if op == 'idesc': return compareCaseInsensitiveDescending
raise ValueError, "Unknown operator: %s"%aString
# Module functions
def _compareUsingKeyOrderArray(object1, object2, sortOrderings):
for ordering in sortOrderings:
key=ordering.key()
cmp=ordering.operator()(object1.valueForKeyPath(key),
object2.valueForKeyPath(key))
if cmp: return cmp
return 0
def sortedArrayUsingKeyOrderArray(array, sortOrderings):
"""
Sorts array with respect to the list of sort commands supplied in
sortOrderings. Object's values are accessed using L{SortOrdering}.key
and L{KeyValueCoding.valueForKeyPath}.
@parameter array: a sequence of objects implementing
L{KeyValueCoding.KeyValueCoding.valueForKeyPath}
@parameter sortOrderings: a sequence of L{SortOrdering} commands.
@return: the sorted array
"""
comp=lambda o1, o2, orderings=sortOrderings:_compareUsingKeyOrderArray(o1,o2,orderings)
result=list(array)
result.sort(comp)
return result
def sortOrderingWithKey(key, operator):
"Alternate constructor for a L{SortOrdering}"
return SortOrdering(key, operator)
def sortOrderingsWithString(str):
"""
Builds a sequence of SortOrdering from the supplied string.
A valid string is: C{<key1> [<operator1>], ..., <key_n> [<operator_n>]}
Valid operators are the one accepted by L{operatorFromString}. When
C{<operator>} is omitted, it defaults to C{'asc'}.
Example of a valid string: C{"name, age desc"} meaning; sort by name
(ascending), then by age (descending).
"""
sorts=[]
parts=str.split(',')
for part in parts:
part=part.strip()
key_op=part.split()
if len(key_op)==1:
key, op=key_op[0], operatorFromString('asc')
elif len(key_op)==2:
key, op=key_op[0], operatorFromString(key_op[1])
else:
raise ValueError, "Unrecognized pattern '%s' in '%s'"%(part, str)
sorts.append(SortOrdering(key,op))
return sorts
#
class SortOrdering:
"""
The canonical sorting command has a key and an operator. The key is the name
of the attribute to use for sorting objects, the operator is the sorting
order (e.g. ascending, descending). Note: the key is in fact more general
than simply the name of an, attribute, since objects' values are accessed
through L{KeyValueCoding} --see L{sortedArrayUsingKeyOrderArray}.
"""
__implements__ = (SortOrderingInterface,)
def __init__(self, key, operator):
self._key=key
if type(operator) is type(''):
operator=operatorFromString(operator)
self._operator=operator
def key(self):
return self._key
def operator(self):
return self._operator
# Static method
sortedArrayUsingKeyOrderArray=staticmethod(sortedArrayUsingKeyOrderArray)
sortOrderingWithKey=staticmethod(sortOrderingWithKey)
|