Example #1
1
    def __new__(cls, *args):
        """Create a new immutable GroupableOrderedDict."""
        new = OrderedDict.__new__(cls)
        OrderedDict.__init__(new)

        if len(args) > 1:
            raise TypeError("expected at most 1 arguments, got {}".format(len(args)))

        ordering = []
        values = args[0]

        if values:
            if isinstance(values, GroupableOrderedDict):
                values = values.iteritems(with_order=False, repeated=True)
            elif isinstance(values, dict):
                if "__order__" in values:
                    order = values.pop("__order__")

                    tmp = []
                    c = Counter()
                    for key in order:
                        v = values[key]
                        if not isinstance(v, (tuple, list)):
                            if c[key] == 0:
                                tmp.append((key, v))
                            else:
                                raise Exception(
                                    "Order and values don't match" "on key {0} at position {1}".format(key, c[key])
                                )
                        else:
                            tmp.append((key, v[c[key]]))
                        c[key] += 1
                    values = tmp
                else:
                    values = iteritems(values)

            for key, value in values:
                if key not in new:
                    OrderedDict.__setitem__(new, key, [])
                v = []
                if isinstance(value, (tuple, list)):
                    for item in value:
                        v.append(item)
                        ordering.append(key)
                else:
                    v.append(value)
                    ordering.append(key)

                OrderedDict.__getitem__(new, key).extend(v)

        # Immutable...
        for key, value in dict.items(new):
            OrderedDict.__setitem__(new, key, tuple(value))

        OrderedDict.__setitem__(new, "__order__", tuple(ordering))
        return new
Example #2
0
    def __new__(cls):
        self = OrderedDict.__new__(cls)

        if not hasattr(cls, "Key"):
            raise TypeError("Mapping classes must define an inner class called 'Key'")

        if not hasattr(cls, "Value"):
            raise TypeError("Mapping classes must define an inner class called 'Value'")

        if not (inspect.isclass(cls.Key) and issubclass(cls.Key, Scalar)):
            raise TypeError("Inner class 'Key' must be a subclass of Scalar")

        if not (inspect.isclass(cls.Value) and issubclass(cls.Value, BaseValue)):
            raise TypeError("Inner class 'Value' must be a subclass of BaseValue")

        return self