Ejemplo n.º 1
0
    def update(*args, **kwds):
        self = args[0]

        with FastInserter(self.cursor):
            MutableMapping.update(*args, **kwds)
            # make table and index stored contiguously
            self.cursor.execute('VACUUM')
Ejemplo n.º 2
0
    def update(self, *args, **kwargs):

        if len(args) > 1:
            raise TypeError("update() takes at most 1 positional "
                            "arguments ({} given)".format(len(args)))
        if len(args) >= 1:
            other = args[0]
            if isinstance(other, KeyedList):
                # Merge
                for key, value in other.all_items():
                    self[key] = value
            else:
                MutableMapping.update(self, other)

        for key, value in kwargs.items():
            if isinstance(value, KeyedList):
                try:
                    subkl = self[key]
                except KeyError:
                    subkl = KeyedList()
                    self[key] = subkl
                else:
                    if not isinstance(subkl, KeyedList):
                        raise KeyError(
                            'target key "%s" is a value, cannot '
                            'update value against another keyed list' %
                            (key, ))
                subkl.update(value)
            else:
                self[key] = value
Ejemplo n.º 3
0
 def __new__(cls, window=None, *args, **kwargs):
     if window is not None:
         if window.id() not in cls.__windows:
             cls.__windows[window.id()] = MutableMapping.__new__(
                 cls, *args, **kwargs)
         return cls.__windows[window.id()]
     return MutableMapping.__new__(cls, *args, **kwargs)
Ejemplo n.º 4
0
def close_store(store: collections.MutableMapping):
    """
    Close *store*, if possible, that is, if *store* has a callable attribute ``close``, call it.
    :param store: The store
    """
    if hasattr(store, 'close') and callable(getattr(store, 'close')):
        store.close()
Ejemplo n.º 5
0
 def __delattr__(self, name):
     # Names starting with an underscore are not preferences but normal
     # instance attributes
     if name.startswith('_'):
         MutableMapping.__delattr__(self, name)
     else:
         del self._all_prefs[self._basename + '.' + name]
Ejemplo n.º 6
0
    def update(*args, **kwds):
        self = args[0]

        with FastInserter(self.cursor):
            MutableMapping.update(*args, **kwds)
            # make table and index stored contiguously
            self.cursor.execute("VACUUM")
Ejemplo n.º 7
0
 def __getattr__(self, name):
     # private and protected attributes at accessed directly
     if name.startswith('_') or name in self._attributesOrig:
         if name.startswith('__'):
             return MutableMapping.__getattribute__(self, name)
         if name not in self._propertiesAllowed:
             return MutableMapping.__getattribute__(self, name)
             return self.__dict__[name]
     op = lambda x: neg(x) if name in self._aliasesNegated else x
     name = self._aliasesNegated.get(name, name)
     name = self._aliases.get(name, name)
     raw = self._propertiesTranslation.get(name, name)
     desc = self._propertiesDescriptor.get(
         raw) or self._relationshipsDescriptor.get(raw)
     if desc:
         return op(desc.__get__(self))
     if self._propertiesAdditional and name in self._data:
         self._itemsInputs[raw] = self._items_inputs_evaluate(name)
         self._dataAdditional[raw] = v = op(self[name])
         return v
     if self._attributeByName:
         try:
             return op(self.resolve_cname([name]))
         except Exception as er:
             self._logger.error(er, exc_info=True)
             raise
     if not self._propertiesAdditional:
         # additional properties not allowed, raise exception
         raise AttributeError("'{0}' is not a valid property of {1}".format(
             name, self.__class__.__name__))
     if name not in self._required:
         return
     raise AttributeError("'{0}' has not been set to {1}".format(
         name, self.__class__.__name__))
    def update(self, *args, **kwargs):

        if len(args) > 1:
            raise TypeError("update() takes at most 1 positional "
                            "arguments ({} given)".format(len(args)))
        if len(args) >= 1:
            other = args[0]
            if isinstance(other, KeyedList):
                # Merge
                for key, value in other.all_items():
                    self[key] = value
            else:
                MutableMapping.update(self, other)

        for key, value in kwargs.items():
            if isinstance(value, KeyedList):
                try:
                    subkl = self[key]
                except KeyError:
                    subkl = KeyedList()
                    self[key] = subkl
                else:
                    if not isinstance(subkl, KeyedList):
                        raise KeyError('target key "%s" is a value, cannot '
                                'update value against another keyed list' %
                                (key,))
                subkl.update(value)
            else:
                self[key] = value
Ejemplo n.º 9
0
 def __delattr__(self, name):
     # Names starting with an underscore are not preferences but normal
     # instance attributes
     if name.startswith('_'):
         MutableMapping.__delattr__(self, name)
     else:
         del self._all_prefs[self._basename + '.' + name]
Ejemplo n.º 10
0
 def __init__(self, *state: tuple):
     MutableMapping.__init__(self)
     MutableComposite.__init__(self)
     try:
         for i, name in enumerate(self._fields):
             setattr(self, name, state[i])
     except IndexError:
         IndexError("Instantiate %s with %u elements, but required are: %s"
                    % (self.__class__.__name__, len(state), self._fields))
Ejemplo n.º 11
0
    def __init__(self, init_registry=None):
        if init_registry:
            if isinstance(init_registry, dict):
                self._registry = copy.deepcopy(init_registry)
            else:
                raise InvalidJWSERegOperation('Unknown input type')
        else:
            self._registry = {}

        MutableMapping.__init__(self)
Ejemplo n.º 12
0
 def __init__(*args, **kwargs):
     if not args:
         raise TypeError("OrderedDict.__init__() needs an instance as the first argument")
     self = args[0]
     args = args[1:]
     if len(args) > 1:
         raise TypeError("OrderedDict() takes at most 1 positional argument, got %d" % len(args))
     dict.__init__(self)
     if not self:
         self._keys = []
     MutableMapping.update(self, *args, **kwargs)
Ejemplo n.º 13
0
 def update(self, *args, **kw):
     if args:
         lst = args[0]
         if len(lst) != len(dict(lst)):
             # this does not catch the cases where we overwrite existing
             # keys, but those would produce too many warning
             msg = ("Behavior of MultiDict.update() has changed "
                 "and overwrites duplicate keys. Consider using .extend()"
             )
             warnings.warn(msg, UserWarning, stacklevel=2)
     MutableMapping.update(self, *args, **kw)
Ejemplo n.º 14
0
 def update(self, *args, **kw):
     if args:
         lst = args[0]
         if len(lst) != len(dict(lst)):
             # this does not catch the cases where we overwrite existing
             # keys, but those would produce too many warning
             msg = (
                 "Behavior of MultiDict.update() has changed "
                 "and overwrites duplicate keys. Consider using .extend()")
             warnings.warn(msg, UserWarning, stacklevel=2)
     MutableMapping.update(self, *args, **kw)
Ejemplo n.º 15
0
 def __init__(*args, **kwargs):
     if not args:
         raise TypeError(
             "OrderedDict.__init__() needs an instance as the first argument"
         )
     self = args[0]
     args = args[1:]
     if len(args) > 1:
         raise TypeError(
             "OrderedDict() takes at most 1 positional argument, got %d" %
             len(args))
     dict.__init__(self)
     if not self:
         self._keys = []
     MutableMapping.update(self, *args, **kwargs)
Ejemplo n.º 16
0
def flatten(d: collections.MutableMapping,
            parent_key: str = '',
            sep: str = '_') -> dict:
    """
    flatten a dict

    credit goes to https://stackoverflow.com/a/6027615/13224997

    Parameters
    ----------
    d : dict
        dictionary to be flattened

    parent_key : str
        used internally for appending to a dict

    sep : str
        separating character in the flattened dict keys

    Returns
    -------
    dict
        the flattened dict.

    """
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.extend(flatten(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)
Ejemplo n.º 17
0
 def __init__(self, query="", sort_keys=False, lower_keys=False, upper_keys=False):
     MutableMapping.__init__(self)
     self._parameters = []
     self._sort_keys = sort_keys
     self._lower_keys = lower_keys
     self._upper_keys = upper_keys
     if isinstance(query, Mapping):
         if isinstance(query, _ParamMap):
             if query.is_sort_keys():
                 self.set_sort_keys()
             if query.is_lower_keys():
                 self.set_lower_keys()
             if query.is_upper_keys():
                 self.set_upper_keys()
         self.update(query)
     elif query is not None:
         self.update(OrderedDict(urlparse.parse_qsl(str(query))))
Ejemplo n.º 18
0
    def __eq__(self, other):
        """ Don't allow objects of different classes to be equal.

        This will allow different instances with different names but the same
        keys and values to be equal. Subclasses may wish to override this to
        compare different attributes.
        """
        if type(other) is not type(self):
            return False
        return DictMixin.__eq__(self, other)
Ejemplo n.º 19
0
    def __eq__(self, other):
        """ Don't allow objects of different classes to be equal.

        This will allow different instances with different names but the same
        keys and values to be equal. Subclasses may wish to override this to
        compare different attributes.
        """
        if type(other) is not type(self):
            return False
        return DictMixin.__eq__(self, other)
Ejemplo n.º 20
0
def introspect(d: collections.MutableMapping,
               parent_key: str = '',
               sep: str = '.') -> dict:
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + str(k) if parent_key else str(k)
        if isinstance(v, collections.MutableMapping):
            items.extend(introspect(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)
Ejemplo n.º 21
0
    def __init__(self):
        MutableMapping.__init__(self)

        self._palette = dict()

        fg_7color_offset = 30
        names = [
            'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan',
            'light_gray'
        ]

        base_code_template = Palette.esc + '[%dm'
        color_codes = {
            name: base_code_template % (i + fg_7color_offset)
            for i, name in enumerate(names)
        }

        bold_style = Palette.esc + '[1m'
        underline_style = Palette.esc + '[4m'

        self._set_palette(color_codes,
                          _bold=bold_style,
                          _underlined=underline_style)
Ejemplo n.º 22
0
def result_to_flat_dict(record: collections.MutableMapping,
                        parent: str = '',
                        sep: str = '__') -> Dict:
    items: List = []
    for k, v in record.items():
        if not parent or k.startswith('weapon'):
            new_key = k
        else:
            new_key = f"{parent}{sep}{k}"

        if isinstance(v, collections.MutableMapping):
            items.extend(result_to_flat_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)
def flatten_dict(
    data: collections.MutableMapping,
    parent_key: str = "",
    sep: Optional[str] = None,
) -> dict:
    """Return nested dict as single level dict."""
    sep = sep or DRF_EXCEPTIONS_SEPARATOR
    items: list = []
    for k, v in data.items():
        new_key = sep.join([parent_key, k]) if parent_key and sep else k
        if isinstance(v, collections.MutableMapping):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)
Ejemplo n.º 24
0
 def __getattr__(self, name):
     if name in self.__dict__ or name.startswith('__'):
         return MutableMapping.__getattr__(self, name)
     
     # This function might get called from BrianGlobalPreferencesView with
     # a prefixed name -- therefore the name can contain dots!
     if name in self.pref_register:
         # This asks for a category, not a single preference
         return BrianGlobalPreferencesView(name, self)
     
     basename, _ = parse_preference_name(name)
     if len(basename) and basename not in self.pref_register:
         raise AssertionError(('__getattr__ received basename %s which is '
                              'unregistered. This should never happen!') %
                              basename)
     
     return self[name]
Ejemplo n.º 25
0
    def __getattr__(self, name):
        if name in self.__dict__:
            return MutableMapping.__getattr__(self, name)

        # This function might get called from BrianGlobalPreferencesView with
        # a prefixed name -- therefore the name can contain dots!
        if name in self.pref_register:
            # This asks for a category, not a single preference
            return BrianGlobalPreferencesView(name, self)

        basename, _ = parse_preference_name(name)
        if len(basename) and basename not in self.pref_register:
            raise AssertionError(
                ('__getattr__ received basename %s which is '
                 'unregistered. This should never happen!') % basename)

        return self[name]
Ejemplo n.º 26
0
def flatten(d: collections.MutableMapping, parent_key='', sep='.') -> dict:
    """flattens directory so there isn't any dict or list in items
    renames keys of nested dictionaries, so that there are no conflicts
    >>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})
    {'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd.0': 1, 'd.1': 2, 'd.2': 3}

    """
    items = []

    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten(v, new_key, sep=sep).items())
        elif isinstance(v, (tuple, list, set)):
            items.extend(
                flatten(
                    dict([(new_key + '.' + str(idx), itm)
                          for idx, itm in enumerate(v)])).items())
        else:
            items.append((new_key, v))
    return dict(items)
Ejemplo n.º 27
0
 def values(self):
     """
     Return a list over of all values in the settings.
     """
     return MutableMapping.values(self)
Ejemplo n.º 28
0
    setdefault = MutableMapping.setdefault

    def update(self, *args, **kw):
        """Like :attr:`putall` with default duplication policies."""
        if args or kw:
            self._update(False, self.on_dup_key, self.on_dup_val,
                         self.on_dup_kv, *args, **kw)

    def forceupdate(self, *args, **kw):
        """Like a bulk :attr:`forceput`."""
        self._update(False, OVERWRITE, OVERWRITE, OVERWRITE, *args, **kw)

    def putall(self,
               items,
               on_dup_key=RAISE,
               on_dup_val=RAISE,
               on_dup_kv=None):
        """
        Like a bulk :attr:`put`.

        If one of the given items causes an exception to be raised,
        none of the items is inserted.
        """
        if items:
            self._update(False, on_dup_key, on_dup_val, on_dup_kv, items)


# MutableMapping does not implement __subclasshook__.
# Must register as a subclass explicitly.
MutableMapping.register(bidict)
Ejemplo n.º 29
0
    if value and isinstance(value[0], list):
        Log.error("not expected")
    old_v = obj.get(key)
    if old_v is None:
        obj[key] = value
    else:
        old_v.extend(value)


class Annotation(ParseResults):
    # Append one of these to the parse results to
    # add key: value pair not found in the original text

    __slots__ = []

    def __init__(self, name, value):
        if not name:
            Log.error("expecting a name")
        if not isinstance(value, list):
            Log.error("expecting a list")
        ParseResults.__init__(self, Empty()(name), value)

    def __str__(self):
        return "{" + text(self.name) + ": " + text(self.tokens) + "}"

    def __repr__(self):
        return "Annotation(" + repr(self.name) + ", " + repr(self.tokens) + ")"


MutableMapping.register(ParseResults)
Ejemplo n.º 30
0
                self.vars[key] = SetWrapper(value)

    def copy(self, *args, **kwargs):
        return type(self)(self.vars.copy(*args, **kwargs))

    def display(self, **kwargs):
        ret = 'Domain('
        strs = [
            '{} = {}'.format(var, vals.display(**kwargs))
            for var, vals in sorted(self.vars.items(), key=itemgetter(0))
        ]
        ret += ',\n       '.join(strs) + ')'
        return ret


MutableMapping.register(Domain)

#-------------------------------------------------------------------------------
# Constraint


class Constraint(Base):
    _attrs = dict(args=Attr(Sequence, init=lambda self: tuple()))
    _opts = dict(init_validate=True, args=('args', ), make_hashable=True)

    def check(self, **kwargs):
        raise NotImplementedError

    def display(self, **kwargs):
        pass
Ejemplo n.º 31
0
 def __len__(self):
     return MutableMapping.__len__(self)
Ejemplo n.º 32
0
                self.vars[key] = TypeWrapper(value)
            else:
                self.vars[key] = SetWrapper(value)

    def copy(self, *args, **kwargs):
        return type(self)(self.vars.copy(*args, **kwargs))

    def display(self, **kwargs):
        ret = 'Domain('
        strs = ['{} = {}'.format(var, vals.display(**kwargs))
                for var, vals in sorted(self.vars.items(), key=itemgetter(0))]
        ret += ',\n       '.join(strs) + ')'
        return ret


MutableMapping.register(Domain)

#-------------------------------------------------------------------------------
# Constraint


class Constraint(Base):
    _attrs = dict(args = Attr(Sequence,
                              init=lambda self: tuple()))
    _opts = dict(init_validate = True,
                 args = ('args',),
                 make_hashable = True)

    def check(self, **kwargs):
        raise NotImplementedError
Ejemplo n.º 33
0
    if sys.version_info[0] == 3:  # pragma: no cover
        items = _iterate_items
        keys = _iterate_keys
        values = _iterate_values
    else:

        def keys(self):
            return list(self)

        def items(self):
            return list(self._iterate_items())

        def values(self):
            return list(self._iterate_values())
MutableMapping.register(DictAttribute)


class ChainMap(MutableMapping):

    key_t = None
    changes = None
    defaults = None
    maps = None

    def __init__(self, *maps, **kwargs):
        maps = list(maps or [{}])
        self.__dict__.update(
            key_t=kwargs.get('key_t'),
            maps=maps,
            changes=maps[0],
Ejemplo n.º 34
0
 def clear(self):
     if len(self._dict) > 0:
         MutableMapping.clear(self)
Ejemplo n.º 35
0
 def clear(self):
     if len(self._dict) > 0:
         MutableMapping.clear(self)
Ejemplo n.º 36
0
    def raw_items(self):
        return [(name, self.__raw(name)) for name in self.keys()]

    def raw_values(self):
        return [self.__raw(name) for name in self.keys()]

    def load(self, context):  # allows to use collection as source
        context.update(self)
        return context
    # end

    def __str__(self):
        return six.u('<Collection: %s>' % [key for key in self.keys()])

    __unicode__ = __repr__ = __str__


MutableMapping.register(Collection)


class Module(ModuleType):
    def __init__(self, module_name, filepath, collection):
        super(Module, self).__init__(module_name)
        self.__file__ = filepath
        for name, value in collection.items():
            setattr(self, name, value)

    def __getitem__(self, name):
        return getattr(self, name)
Ejemplo n.º 37
0
    else:

        def keys(self):
            # type: () -> List[Any]
            return list(self)

        def items(self):
            # type: () -> List[Tuple[Any, Any]]
            return list(self._iterate_items())

        def values(self):
            # type: () -> List[Any]
            return list(self._iterate_values())


MutableMapping.register(DictAttribute)  # noqa: E305


class ChainMap(MutableMapping):
    """Key lookup on a sequence of maps."""

    key_t = None
    changes = None
    defaults = None
    maps = None

    def __init__(self, *maps, **kwargs):
        # type: (*Mapping, **Any) -> None
        maps = list(maps or [{}])
        self.__dict__.update(
            key_t=kwargs.get('key_t'),
Ejemplo n.º 38
0
    __iter__ = iterkeys

    def __reversed__(self):
        """Iterate over the values in the cache dict, oldest items
        coming first.
        """
        return iter(tuple(self._queue))

    __copy__ = copy


# register the LRU cache as mutable mapping if possible
try:
    from collections import MutableMapping
    MutableMapping.register(LRUCache)
except ImportError:
    pass


class Cycler(object):
    """A cycle helper for templates."""

    def __init__(self, *items):
        if not items:
            raise RuntimeError('at least one item has to be provided')
        self.items = items
        self.reset()

    def reset(self):
        """Resets the cycle."""
Ejemplo n.º 39
0
	def clear(self):
		"""Empty the backing store of data."""
		
		self.__data__.clear()
	
	def pop(self, name, default=SENTINEL):
		"""Retrieve and remove a value from the backing store, optionally with a default."""
		
		if default is SENTINEL:
			return self.__data__.pop(name)
		
		return self.__data__.pop(name, default)
	
	def popitem(self):
		"""Pop an item 2-tuple off the backing store."""
		
		return self.__data__.popitem()
	
	def update(self, *args, **kw):
		"""Update the backing store directly."""
		
		self.__data__.update(*args, **kw)
	
	def setdefault(self, key, value=None):
		"""Set a value in the backing store if no value is currently present."""
		
		return self.__data__.setdefault(key, value)


MutableMapping.register(Document)  # Metaclass conflict if we subclass.
Ejemplo n.º 40
0
 def __init__(self, **kwargs):
   MutableMapping.__init__(self)
   self.modifications = {}
   """ Holds chemical modifications. """
   self.breaksym = kwargs.get('breaksym', not kwargs.get('keepsymm', False))
   """ Whether to break symmetries or not. """
Ejemplo n.º 41
0
 def clear(self):
     self._root = _Link()
     self._map.clear()
     MutableMapping.clear(self)
Ejemplo n.º 42
0
        """Identify if this URI is relative to some "current context".
		
		For example, if the protocol is missing, it's protocol-relative. If the host is missing, it's host-relative, etc.
		"""

        scheme = self.scheme

        if not scheme:
            return True

        return scheme.is_relative(self)

    def resolve(self, uri=None, **parts):
        """Attempt to resolve a new URI given an updated URI, partial or complete."""

        if uri:
            result = self.__class__(urljoin(str(self), str(uri)))
        else:
            result = self.__class__(self)

        for part, value in parts.items():
            if part not in self.__all_parts__:
                raise TypeError("Unknown URI component: " + part)

            setattr(result, part, value)

        return result


MutableMapping.register(URI)
Ejemplo n.º 43
0
 def __init__(self, *args, **kwargs):
     MutableMapping.__init__(self)
     dict.__init__(self)
     self._root = _Link()
     self._map = {}
     self.update(*args, **kwargs)
Ejemplo n.º 44
0
    else:

        def keys(self):
            # type: () -> List[Any]
            return list(self)

        def items(self):
            # type: () -> List[Tuple[Any, Any]]
            return list(self._iterate_items())

        def values(self):
            # type: () -> List[Any]
            return list(self._iterate_values())


MutableMapping.register(DictAttribute)  # noqa: E305


class ChainMap(MutableMapping):
    """Key lookup on a sequence of maps."""

    key_t = None
    changes = None
    defaults = None
    maps = None

    def __init__(self, *maps, **kwargs):
        # type: (*Mapping, **Any) -> None
        maps = list(maps or [{}])
        self.__dict__.update(
            key_t=kwargs.get('key_t'),
Ejemplo n.º 45
0
    def get(self, key, default=None):
        """Return value for given ``key`` or ``default`` value."""
        try:
            return self[key]
        except KeyError:
            return default

    def set(self, key, value, extend=False, **kwargs):
        """Extended standard set function."""
        self.__setitem__(key, value, extend, **kwargs)

    def update(self, E, **F):
        """Proxy `dict` update method."""
        self._dict.update(E, **F)

MutableMapping.register(SmartDict)


class DotableDict(dict):

    """Make nested python dictionaries accessable using dot notation.

    Example:

    .. code-block:: python

        >>> dotable = DotableDict({'a': [{'b': 3, 'c': 5}]})
        >>> dotable.a
        ...  [{'b': 3, 'c': 5}]
    """
Ejemplo n.º 46
0
 def __new__(cls, window=None, *args, **kwargs):
     if window is not None:
         if window.id() not in cls.__windows:
             cls.__windows[window.id()] = MutableMapping.__new__(cls, *args, **kwargs)
         return cls.__windows[window.id()]
     return MutableMapping.__new__(cls, *args, **kwargs)
Ejemplo n.º 47
0
from collections import MutableMapping

from ._sortedmap import sortedmap


MutableMapping.register(sortedmap)
del MutableMapping


__version__ = '0.2.0'


__all__ = [
    'sortedmap',
]
Ejemplo n.º 48
0
 def __setattr__(self, name, value):
     # Do not allow to set a category name to something else
     if 'pref_register' in self.__dict__ and name in self.pref_register:
         raise PreferenceError('Cannot set a preference category.')
     else:
         MutableMapping.__setattr__(self, name, value)
Ejemplo n.º 49
0
        result = sdict()
        for key, value_set in self.iteritems():
            for value in value_set:
                result._get_or_create(value).add(key)
        return result

    def delete(self, value):
        """
        Delete a value in all value sets and delete resulting empty items.

        Returns removed_from and deleted sets of keys.
        """
        removed_from = set()
        deleted = set()
        for key, value_set in self.iteritems():
            try:
                value_set.remove(value)
            except KeyError:
                continue
            removed_from.add(key)
            if not value_set:
                deleted.add(key)
        for key in deleted:
            self.pop(key)
        return removed_from, deleted

    def union(self):
        return set.union(*self.values())

MutableMapping.register(sdict)
Ejemplo n.º 50
0
 def __delattr__(self, name):
     if 'pref_register' in self.__dict__ and name in self.pref_register:
         raise PreferenceError('Cannot delete a preference category.')
     else:
         MutableMapping.__setattr__(self, name, value)
Ejemplo n.º 51
0
        return (tuple(bucket) for bucket in self.buckets)

    def values(self):  # Mapping
        return (bucket.value for bucket in self.buckets)

    def get(self, bucket, default=None):  # Mapping
        if bucket in self:
            return self[bucket]

        return default

    def clear(self):  # MutableMapping
        """Clear all values from this query string object."""

        del self.buckets[:]
        self.groups.clear()

    def update(self, *args, **kw):  # MutableMapping
        for parts in args:
            for bucket in self._parts(parts):
                bucket = Bucket(bucket,
                                sep=self.assignment,
                                strict=self.strict)
                self[bucket.name] = bucket.value

        for key in kw:
            self[key] = kw[key]


MutableMapping.register(QSO)
Ejemplo n.º 52
0
 def popitem(self, last=True):
     if not self:
         raise KeyError("dict is empty")
     key = next(reversed(self) if last else iter(self))
     return key, MutableMapping.pop(self, key)
Ejemplo n.º 53
0
    __iter__ = iterkeys

    def __reversed__(self):
        """Iterate over the values in the cache dict, oldest items
        coming first.
        """
        return iter(tuple(self._queue))

    __copy__ = copy


# register the LRU cache as mutable mapping if possible
try:
    from collections import MutableMapping
    MutableMapping.register(LRUCache)
except ImportError:
    pass


@implements_iterator
class Cycler(object):
    """A cycle helper for templates."""

    def __init__(self, *items):
        if not items:
            raise RuntimeError('at least one item has to be provided')
        self.items = items
        self.reset()

    def reset(self):
Ejemplo n.º 54
0
 def __repr__(self):
     if not self.alive:
         return 'Dead CrossView{ }'
     return 'CrossView' + DictMixin.__repr__(self)
Ejemplo n.º 55
0
        self._bwd = merged._bwd

    def _proxied_to_fwd(method):
        """
        Decorator which proxies calls to the given bidict method on to the
        self._fwd dict.
        """
        @wraps(method, ('__name__', '__doc__'))
        def wrapper(self, *args, **kwds):
            return method(self._fwd, *args, **kwds)
        return wrapper

    for methodname in '__contains__ __iter__ __len__ get keys items values'.split():
        locals()[methodname] = _proxied_to_fwd(getattr(dict, methodname))

MutableMapping.register(bidict)


# thanks to Raymond Hettinger for the idea for namedbidict

_LEGALNAMEPAT = '^[a-zA-Z][a-zA-Z0-9_]*$'
_LEGALNAMERE = re.compile(_LEGALNAMEPAT)

def namedbidict(mapname, fwdname, invname):
    """
    Generate a custom bidict class in the spirit of ``namedtuple`` with
    custom attribute-based access to forward and inverse mappings::

        >>> CoupleMap = namedbidict('CoupleMap', 'husbands', 'wives')
        >>> famous = CoupleMap({'bill': 'hillary'})
        >>> famous.husbands['bill']
Ejemplo n.º 56
0
 def __setattr__(self, name, value):  
     # Do not allow to set a category name to something else
     if 'pref_register' in self.__dict__ and name in self.pref_register:
         raise PreferenceError('Cannot set a preference category.')
     else:
         MutableMapping.__setattr__(self, name, value)      
Ejemplo n.º 57
0
    if sys.version_info[0] == 3:  # pragma: no cover
        items = _iterate_items
        keys = _iterate_keys
        values = _iterate_values
    else:

        def keys(self):
            return list(self)

        def items(self):
            return list(self._iterate_items())

        def values(self):
            return list(self._iterate_values())
MutableMapping.register(DictAttribute)


class ConfigurationView(AttributeDictMixin):
    """A view over an applications configuration dicts.

    Custom (but older) version of :class:`collections.ChainMap`.

    If the key does not exist in ``changes``, the ``defaults`` dicts
    are consulted.

    :param changes:  Dict containing changes to the configuration.
    :param defaults: List of dicts containing the default configuration.

    """
    key_t = None
Ejemplo n.º 58
0
 def __delattr__(self, name):
     if 'pref_register' in self.__dict__ and name in self.pref_register:
         raise PreferenceError('Cannot delete a preference category.')
     else:
         MutableMapping.__setattr__(self, name, value)