SortOrdering.py :  » Database » Modeling-Framework » Modeling-0.9 » Modeling » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Database » Modeling Framework 
Modeling Framework » Modeling 0.9 » Modeling » SortOrdering.py
# -*- 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)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.