"""
Simple Set Class
Note that we cannot use the sets.Set class of Python2.3 here,
because we want items() as sorted list
"""
#  Copyright (C) 2004  Henning Jacobs <henning@srcco.de>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  $Id: Set.py 82 2004-07-11 13:01:44Z henning $

def union(s1, s2):
    import copy
    result = copy.copy(s1)
    for item in s2:
        result.add(item)
    return result

class Set:
    def __init__(self, *args):
        self._dict = {}
        for arg in args:
            self.add(arg)
    def __repr__(self):
        import string
        elems = map(repr, self._dict.keys())
        elems.sort()
        return "%s(%s)" % (self.__class__.__name__, string.join(elems, ", "))
    def assign(self, other):
        import copy
        self._dict = copy.copy(other._dict)
    def extend(self, args):
        "Add several items at once."
        for arg in args:
            self.add(arg)
    def add(self, item):
        "Add one item to the set."
        self._dict[item] = item
    def remove(self, item):
        "Remove an item from the set."
        del self._dict[item]
    def contains(self, item):
        "Check whether the set contains a certain item."
        return self._dict.has_key(item)
    # High-Performance membership test for Python 2.0+
    __contains__ = contains
    def __getitem__(self, index):
        "Support the 'for item in set:' proto."
        return self._dict.keys()[index]
    def __iter__(self):
        "Better support 'for item in set:' via Py2.2 iterators"
        return iter(self._dict.copy())
    def __len__(self):
        "Return the number of items in the set."
        return len(self._dict)
    def items(self):
        "Return a list containing all items in sorted order, if possible."
        result = self._dict.keys()
        try: result.sort()
        except: pass
        return result

