On 10/29/07, mmstud <[EMAIL PROTECTED]> wrote:
> Thats handy. Where could i get the utils module you're using for Enum
> datatype?

The Enum datatype is from the ASPN cookbook, with type bindings for
SA. Here's part of my utils module.

cheers,
Arnar

# -*- encoding: UTF-8 -*-

import sqlalchemy.types as types
import datetime, time
from itertools import groupby

def numericSort(alist, val=lambda x: x):
   """Returns a copy. See recipe 135435 on aspn"""
   def genidx(str):
      index = []
      def _append(fragment, alist=index):
         if fragment.isdigit(): fragment = int(fragment)
         alist.append(fragment)

      prev_isdigit = str[0].isdigit()
      current_fragment = ''
      for char in str:
         curr_isdigit = char.isdigit()
         if curr_isdigit == prev_isdigit:
            current_fragment += char
         else:
            _append(current_fragment)
            current_fragment = char
            prev_isdigit = curr_isdigit
      _append(current_fragment)
      return tuple(index)

   indicies = map(genidx, map(val, alist))
   decorated = zip(indicies, alist)
   decorated.sort()
   return [item for idx, item in decorated]

# From ASPN cookbook, Zoran Isailovski
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486)
# Added JSON and SQLAlchemy handles
def Enum(*names):
    ##assert names, "Empty enums are not supported" # <- Don't like
empty enums? Uncomment!

    class EnumClass(types.TypeDecorator):
        __slots__ = names
        impl = types.Integer
        def __iter__(self):        return iter(constants)
        def __len__(self):         return len(constants)
        def __getitem__(self, i):  return constants[i]
        def __repr__(self):        return 'Enum' + str(names)
        def __str__(self):         return 'enum ' + str(constants)
        def convert_bind_param(self, value, engine): return value.Value
        def convert_result_value(self, value, engine): return self[value]

    class EnumValue(object):
        __slots__ = ('__value')
        def __init__(self, value): self.__value = value
        Value = property(lambda self: self.__value)
        EnumType = property(lambda self: EnumType)
        def __hash__(self):        return hash(self.__value)
        def __cmp__(self, other):
            if type(other) is str:
                return cmp(str(self), other)
            elif type(other) is unicode:
                return cmp(str(self), str(other))
            else:
                # C fans might want to remove the following assertion
                # to make all enums comparable by ordinal value {;))
                assert self.EnumType is other.EnumType, "Only values
from the same enum are comparable"
                return cmp(self.__value, other.__value)
        def __invert__(self):      return constants[maximum - self.__value]
        def __nonzero__(self):     return bool(self.__value)
        def __repr__(self):        return str(names[self.__value])
        def __json__(self):        return str(names[self.__value])

    maximum = len(names) - 1
    constants = [None] * len(names)
    for i, each in enumerate(names):
        val = EnumValue(i)
        setattr(EnumClass, each, val)
        constants[i] = val
    constants = tuple(constants)
    EnumType = EnumClass()
    return EnumType

class Region(object):

    def __init__(self, left, top, width, height):
        self.left = left
        self.top = top
        self.width = width
        self.height = height

    def __str__(self):
        return "Region(%d,%d,%d,%d)" %
(self.left,self.top,self.width,self.height)

    def __repr__(self):
        return str(self)

def countdistinct(iterable, groups=None, key=None):
    """Count things.

    >>> items = ['red', 'green', 'blue', 'blue']
    >>> countdistinct(items)
    {'blue': 2, 'green': 1, 'red': 1}

    You can ensure that specific groups are always included in the result, even
    if they don't occur in the input:

    >>> items = ['red', 'blue', 'blue']
    >>> countdistinct(items, groups=['red', 'green', 'blue'])
    {'blue': 2, 'green': 0, 'red': 1}

    The optional `key` argument can be used to provide a function that returns
    the comparison key for every item:

    >>> from operator import itemgetter
    >>> items = [dict(name='foo', category='buzz'),
    ...          dict(name='bar', category='buzz')]
    >>> print countdistinct(items, key=itemgetter('category'))
    {'buzz': 2}
    """
    if groups is None: groups = []
    d = dict([(g, 0) for g in groups])
    for g, l in groupby(iterable, key=key):
        d[g] = len(list(l)) + d.get(g, 0)
    return d

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to