コード例 #1
0
ファイル: results.py プロジェクト: joshis1/JavaScript
        """
        Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the
        name-value relations as results names. If an optional ``name`` argument is
        given, a nested ``ParseResults`` will be returned.
        """
        def is_iterable(obj):
            try:
                iter(obj)
            except Exception:
                return False
            else:
                return not isinstance(obj, str_type)

        ret = cls([])
        for k, v in other.items():
            if isinstance(v, Mapping):
                ret += cls.from_dict(v, name=k)
            else:
                ret += cls([v], name=k, asList=is_iterable(v))
        if name is not None:
            ret = cls([ret], name=name)
        return ret

    asList = as_list
    asDict = as_dict
    getName = get_name


MutableMapping.register(ParseResults)
MutableSequence.register(ParseResults)
コード例 #2
0
ファイル: multiset.py プロジェクト: wheerd/multiset
        Makes the *default* argument of the original :meth:`dict.setdefault` non-optional.

        Args:
            element: The element which is added if not already present.
            default: The default multiplicity to add the element with if not in the multiset.

        Returns:
            The multiplicity for *element* if it is in the multiset, else *default*.
        """
        return self._elements.setdefault(element, default)

    def clear(self):
        """Empty the multiset."""
        self._elements.clear()
        self._total = 0


class FrozenMultiset(BaseMultiset):
    """The frozen multiset variant that is immutable and hashable."""
    __slots__ = ()

    def __hash__(self):
        return hash(frozenset(self._elements.items()))

Mapping.register(BaseMultiset)  # type: ignore
MutableMapping.register(Multiset)  # type: ignore

if __name__ == '__main__':
    import doctest
    doctest.testmod()
コード例 #3
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.abc import MutableMapping
    MutableMapping.register(LRUCache)
except ImportError:
    pass


def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::
コード例 #4
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'),
コード例 #5
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
    _observers = []

    def __init__(self, *maps, **kwargs):
        # type: (*Mapping, **Any) -> None
        maps = list(maps or [{}])
        self.__dict__.update(
コード例 #6
0
    iteritems = _iterate_items

    def _iterate_values(self):
        # type: () -> Iterable
        for key in self._iterate_keys():
            yield getattr(self.obj, key)

    itervalues = _iterate_values

    items = _iterate_items
    keys = _iterate_keys
    values = _iterate_values


MutableMapping.register(DictAttribute)


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

    key_t = None
    changes = None
    defaults = None
    maps = None
    _observers = []

    def __init__(self, *maps, **kwargs):
        # type: (*Mapping, **Any) -> None
        maps = list(maps or [{}])
        self.__dict__.update(
コード例 #7
0
ファイル: _GenericMap.py プロジェクト: lsst/afw
        for key, value in self.items():
            try:
                if (value != other[key]):
                    return False
            except KeyError:
                return False
        return True

    # Easier than making GenericMap actually inherit from Mapping
    keys = Mapping.keys
    values = Mapping.values
    items = Mapping.items


MutableMapping.register(MutableGenericMapS)

@continueClass  # noqa F811
class MutableGenericMapS:
    # Easier than making MutableGenericMap actually inherit from MutableMapping
    setdefault = MutableMapping.setdefault
    update = MutableMapping.update

    # MutableMapping.pop relies on implementation details of MutableMapping
    def pop(self, key, default=None):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not None:
コード例 #8
0
ファイル: utils.py プロジェクト: dpmatthews/cylc
    __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.abc import MutableMapping
    MutableMapping.register(LRUCache)
except ImportError:
    pass


def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::
コード例 #9
0
ファイル: _GenericMap.py プロジェクト: lsst/afw
    # MutableMapping.pop relies on implementation details of MutableMapping
    def pop(self, key, default=None):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not None:
                return default
            else:
                raise


MutableGenericMap.register(str, MutableGenericMapS)
MutableMapping.register(MutableGenericMapS)


class AutoKeyMeta(TemplateMeta):
    """A metaclass for abstract mappings whose key type is implied by their
    constructor arguments.

    This metaclass requires that the mapping have a `dict`-like constructor,
    i.e., it takes a mapping or an iterable of key-value pairs as its first
    positional parameter.

    This class differs from `~lsst.utils.TemplateMeta` only in that the dtype
    (or equivalent) constructor keyword is optional. If it is omitted, the
    class will attempt to infer it from the first argument.
    """
    def __call__(cls, *args, **kwargs):  # noqa N805, non-self first param
コード例 #10
0
limitations under the License.
"""

__version__ = "0.2.0"

from ctools import _ctools

build_with_debug = _ctools.build_with_debug
strhash = _ctools.strhash
int8_to_datetime = _ctools.int8_to_datetime
jump_consistent_hash = _ctools.jump_consistent_hash

try:
    from collections.abc import MutableMapping  # noqa
except ImportError:
    from collections import MutableMapping  # noqa

CacheMap = _ctools.CacheMap
TTLCache = _ctools.TTLCache
Channel = _ctools.Channel
SortedMap = _ctools.SortedMap

try:
    MutableMapping.register(CacheMap)
    MutableMapping.register(TTLCache)
    MutableMapping.register(SortedMap)
except Exception:  # noqa
    pass

del _ctools, MutableMapping