Ejemplo n.º 1
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.º 2
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.º 3
0
            default = Unset if count == 0 else args[0]
            if _SECTION_SEP in option:
                default = None if count == 0 else args[0]
                section, option = option.split(_SECTION_SEP)
                return self.wrapped.misc[section].setdefault(option, default)
            else:
                if count == 0:
                    opt = self.wrapped.casts.get(option)
                    default = opt.my_default if opt else None
                else:
                    default = args[0]
                return self.wrapped.options.setdefault(option, default)
        else:
            msg = "setdefault expected at most 2 arguments, got %s"
            raise TypeError(msg % count + 1)


MutableMapping.register(MetaOptions)


class options(metaclass(MetaOptions)):
    """The single instance of :class:`MetaOptions` that wraps
    ``openerp.tools.config``.

    """


del metaclass
del MutableMapping
Ejemplo n.º 4
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.º 5
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.º 6
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.º 7
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.º 8
0
from collections import MutableMapping

from ._sortedmap import sortedmap


MutableMapping.register(sortedmap)
del MutableMapping


__version__ = '0.2.0'


__all__ = [
    'sortedmap',
]
Ejemplo n.º 9
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.º 10
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.º 11
0
        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.º 12
0
    iteritems = _iterate_items

    def _iterate_values(self):
        return (self[key] for key in self)
    itervalues = _iterate_values

    def keys(self):
        return list(self._iterate_keys())

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

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


class LimitedSet(object):
    """Kind-of Set with limitations.

    Good for when you need to test for membership (`a in set`),
    but the list might become to big, so you want to limit it so it doesn't
    consume too much resources.

    :keyword maxlen: Maximum number of members before we start
                     evicting expired members.
    :keyword expires: Time in seconds, before a membership expires.

    """
    __slots__ = ('maxlen', 'expires', '_data', '__len__', '_heap')
Ejemplo n.º 13
0
        if isinstance(item, Undefined):
            raise KeyError(key)
        return item

    def __repr__(self):
        return '<%s %s of %r>' % (
            self.__class__.__name__,
            repr(self.get_all()),
            self.name
        )


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


class TemplateReference(object):
    """The `self` in templates."""

    def __init__(self, context):
        self.__context = context

    def __getitem__(self, name):
        func = self.__context.blocks[name][0]
        wrap = self.__context.environment.autoescape and \
               Markup or (lambda x: x)
        render = lambda: wrap(concat(func(self.__context)))
Ejemplo n.º 14
0
from _sparsedict import SparseDict

try:
    from collections import MutableMapping
except ImportError:
    pass
else:
    MutableMapping.register(SparseDict)
    del MutableMapping
Ejemplo n.º 15
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.º 16
0
from collections import MutableMapping

from ._sortedmap import sortedmap

MutableMapping.register(sortedmap)
del MutableMapping

__version__ = '0.2.0'

__all__ = [
    'sortedmap',
]
Ejemplo n.º 17
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.º 18
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.º 19
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.º 20
0
        return (self[key] for key in self)

    itervalues = _iterate_values

    def keys(self):
        return list(self._iterate_keys())

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

    def values(self):
        return list(self._iterate_values())


if MutableMapping:
    MutableMapping.register(ConfigurationView)


class LimitedSet(object):
    """Kind-of Set with limitations.

    Good for when you need to test for membership (`a in set`),
    but the list might become to big, so you want to limit it so it doesn't
    consume too much resources.

    :keyword maxlen: Maximum number of members before we start
                     evicting expired members.
    :keyword expires: Time in seconds, before a membership expires.

    """
    __slots__ = ('maxlen', 'expires', '_data', '__len__', '_heap')
Ejemplo n.º 21
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.º 22
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.º 23
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.º 24
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.º 25
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.º 26
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.º 27
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.º 28
0
		if default is SENTINEL:
			return self.operations.pop(name)
		
		return self.operations.pop(name, default)
	
	def popitem(self):
		return self.operations.popitem()
	
	def update(self, *args, **kw):
		self.operations.update(*args, **kw)
	
	def setdefault(self, key, value=None):
		return self.operations.setdefault(key, value)


MutableMapping.register(Ops)  # Metaclass conflict if we subclass.


class Op(Container):
	field = Attribute(default=None)
	operation = Attribute(default=None)
	value = Attribute(default=SENTINEL)
	
	def __repr__(self):
		return "Op({})".format(repr(self.as_query))
	
	def clone(self, **kw):
		arguments = dict(field=self.field, operation=self.operation, value=self.value)
		arguments.update(kw)
		return self.__class__(**arguments)