Python collections.abc 模块,MutableMapping() 实例源码

我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用collections.abc.MutableMapping()

项目:pypyr-cli    作者:pypyr    | 项目源码 | 文件源码
def get_parsed_context(context_arg):
    """Parse input context string and returns context as dictionary."""
    assert context_arg, ("pipeline must be invoked with --context set. For "
                         "this yaml parser you're looking for something "
                         "like --context './myyamlfile.yaml'")
    logger.debug("starting")
    logger.debug(f"attempting to open file: {context_arg}")
    with open(context_arg) as yaml_file:
        payload = yaml.safe_load(yaml_file)

    logger.debug(f"yaml file parsed. Count: {len(payload)}")

    if not isinstance(payload, MutableMapping):
        raise TypeError("yaml input should describe a dictionary at the top "
                        "level. You should have something like "
                        "\n'key1: value1'\n key2: value2'\n"
                        "in the yaml top-level, not \n'- value1\n - value2'")

    logger.debug("done")
    return payload
项目:demo-day-vikings    作者:Mester    | 项目源码 | 文件源码
def flatten(d, parent_key='', sep='_'):
    """Flatten a dictionary of dictionaries"""
    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)
项目:stellarmagnate    作者:abadger    | 项目源码 | 文件源码
def _merge_mapping(merge_to, merge_from, inplace=False):
    """
    As opposed to dict.update, this will recurse through a dictionary's values merging new keys with old ones

    This is an in-place merge.

    :arg merge_to: dictionary to merge into
    :arg merge_from: dictionary to merge from
    :kwarg inplace: If True, merge_to will be modified directly.  If False, a copy of merge_to will
        be modified.
    :returns: the combined dictionary.  If inplace is True, then this is the same as merge_to after
        calling this function
    """
    if inplace:
        dest = merge_to
    else:
        dest = merge_to.copy()

    for key, val in list(merge_from.items()):
        if key in dest and isinstance(dest[key], MutableMapping) and \
                isinstance(val, MutableMapping):
            # Dict value so merge the value
            dest[key] = _merge_mapping(dest[key], val, inplace=inplace)
        else:
            dest[key] = val

    return dest
项目:orange3-educational    作者:biolab    | 项目源码 | 文件源码
def _merge_dicts(master, update):
    """Merge dicts recursively in place (``master`` is modified)"""
    for k, v in master.items():
        if k in update:
            if isinstance(v, MutableMapping) and isinstance(update[k], MutableMapping):
                update[k] = _merge_dicts(v, update[k])
    master.update(update)
    return master
项目:orange3-educational    作者:biolab    | 项目源码 | 文件源码
def chart(self, options=None, *,
              highchart=None, javascript='', javascript_after='', **kwargs):
        """ Populate the webview with a new Highcharts JS chart.

        Parameters
        ----------
        options, highchart, javascript, **kwargs:
            The parameters are the same as for the object constructor.
        javascript_after: str
            Same as `javascript`, except that the code is evaluated
            after the chart, available as ``window.chart``, is created.

        Notes
        -----
        Passing ``{ series: [{ data: some_data }] }``, if ``some_data`` is
        a numpy array, it is **more efficient** to leave it as numpy array
        instead of converting it ``some_data.tolist()``, which is done
        implicitly.
        """
        options = (options or {}).copy()
        if not isinstance(options, MutableMapping):
            raise ValueError('options must be dict')

        if kwargs:
            _merge_dicts(options, _kwargs_options(kwargs))
        self.exposeObject('pydata', options)
        highchart = highchart or self.highchart or 'Chart'
        self.evalJS('''
            {javascript};
            window.chart = new Highcharts.{highchart}(pydata); 0;
            {javascript_after};
        '''.format(javascript=javascript,
                   javascript_after=javascript_after,
                   highchart=highchart,))
项目:pypyr-cli    作者:pypyr    | 项目源码 | 文件源码
def run_step(context):
    """Loads a yaml file into the pypyr context.

    Yaml parsed from the file will be merged into the pypyr context. This will
    overwrite existing values if the same keys are already in there.
    I.e if file yaml has {'eggs' : 'boiled'} and context {'eggs': 'fried'}
    already exists, returned context['eggs'] will be 'boiled'.

    Args:
        context: pypyr.context.Context. Mandatory.
                 The following context key must exist
                - fetchYamlPath. path-like. Path to file on disk.

    Returns:
        None. updates context arg.

    Raises:
        FileNotFoundError: take a guess
        pypyr.errors.KeyNotInContextError: fetchYamlPath missing in context.
        pypyr.errors.KeyInContextHasNoValueError: fetchYamlPath exists but is
                                                  None.
    """
    logger.debug("started")
    context.assert_key_has_value(key='fetchYamlPath', caller=__name__)

    file_path = context.get_formatted('fetchYamlPath')

    logger.debug(f"attempting to open file: {file_path}")
    with open(file_path) as yaml_file:
        payload = yaml.safe_load(yaml_file)

    if not isinstance(payload, MutableMapping):
        raise TypeError("yaml input should describe a dictionary at the top "
                        "level. You should have something like "
                        "\n'key1: value1'\n key2: value2'\n"
                        "in the yaml top-level, not \n'- value1\n - value2'")

    logger.debug("yaml file loaded. Merging into pypyr context. . .")
    context.update(payload)
    logger.info(f"yaml file merged into pypyr context. Count: {len(payload)}")
    logger.debug("done")
项目:orange3-timeseries    作者:biolab    | 项目源码 | 文件源码
def _merge_dicts(master, update):
    """Merge dicts recursively in place (``master`` is modified)"""
    for k, v in master.items():
        if k in update:
            if isinstance(v, MutableMapping) and isinstance(update[k], MutableMapping):
                update[k] = _merge_dicts(v, update[k])
    master.update(update)
    return master
项目:orange3-timeseries    作者:biolab    | 项目源码 | 文件源码
def chart(self, options=None, *,
              highchart=None, javascript='', javascript_after='', **kwargs):
        """ Populate the webview with a new Highcharts JS chart.

        Parameters
        ----------
        options, highchart, javascript, **kwargs:
            The parameters are the same as for the object constructor.
        javascript_after: str
            Same as `javascript`, except that the code is evaluated
            after the chart, available as ``window.chart``, is created.

        Notes
        -----
        Passing ``{ series: [{ data: some_data }] }``, if ``some_data`` is
        a numpy array, it is **more efficient** to leave it as numpy array
        instead of converting it ``some_data.tolist()``, which is done
        implicitly.
        """
        options = (options or {}).copy()
        if not isinstance(options, MutableMapping):
            raise ValueError('options must be dict')

        if kwargs:
            _merge_dicts(options, _kwargs_options(kwargs))
        self.exposeObject('pydata', options)
        highchart = highchart or self.highchart or 'Chart'
        self.evalJS('''
            {javascript};
            window.chart = new Highcharts.{highchart}(pydata); 0;
            {javascript_after};
        '''.format(javascript=javascript,
                   javascript_after=javascript_after,
                   highchart=highchart,))
项目:multidict    作者:aio-libs    | 项目源码 | 文件源码
def test_abc_inheritance():
    assert issubclass(MultiMapping, Mapping)
    assert not issubclass(MultiMapping, MutableMapping)
    assert issubclass(MutableMultiMapping, Mapping)
    assert issubclass(MutableMultiMapping, MutableMapping)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_MutableMapping(self):
        for sample in [dict]:
            self.assertIsInstance(sample(), MutableMapping)
            self.assertTrue(issubclass(sample, MutableMapping))
        self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__',
            '__getitem__', '__setitem__', '__delitem__')
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_abc(self):
        self.assertIsInstance(OrderedDict(), MutableMapping)
        self.assertTrue(issubclass(OrderedDict, MutableMapping))
项目:deoplete-latex    作者:poppyschmo    | 项目源码 | 文件源码
def fake_deepdiff(one, two, indent=4, path=None, strict_strings=None):
    """Compare two term dictionaries. ``strict_strings=False`` treats
    strings that contain the same combination of words as equal.
    """
    for k, v in one.items():
        _one = v
        _two = two.get(k)
        if _one == _two:
            continue
        if all(isinstance(d, abc.MutableMapping) for d in (_one, _two)):
            _path = path if path is not None else []
            _path += ['{:<{width}}{}'.format('', k, width=indent)]
            fake_deepdiff(_one, _two, indent + 4, _path, strict_strings)
            continue
        if (all(isinstance(l, abc.MutableSequence) for l in (_one, _two)) and
                set(tuple(x) for x in _one if isinstance(x, abc.Sequence)) ==
                set(tuple(x) for x in _two if isinstance(x, abc.Sequence))):
            continue
        if all(isinstance(l, str) for l in (_one, _two)):
            if (strict_strings is False and
                    set(c.strip(';:,.?=_-\n') for c in _one.split()) ==
                    set(c.strip(';:,.?=_-\n') for c in _two.split())):
                continue
            else:
                _one = _one.strip().replace('\n', '')
                _two = _two.strip().replace('\n', '')
        print('\n'.join(path) if path else '')
        print('{:<{width}}{}'.format('', k, width=indent))
        print('{:<{width}}one: {}'.format('', _one, width=indent + 4))
        print('{:<{width}}two: {}'.format('', _two, width=indent + 4))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_MutableMapping(self):
        for sample in [dict]:
            self.assertIsInstance(sample(), MutableMapping)
            self.assertTrue(issubclass(sample, MutableMapping))
        self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__',
            '__getitem__', '__setitem__', '__delitem__')
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_abc(self):
        self.assertIsInstance(OrderedDict(), MutableMapping)
        self.assertTrue(issubclass(OrderedDict, MutableMapping))
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def test_mutable_instance_check():
    assert isinstance(Multiset(), MutableMapping)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_MutableMapping(self):
        for sample in [dict]:
            self.assertIsInstance(sample(), MutableMapping)
            self.assertTrue(issubclass(sample, MutableMapping))
        self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__',
            '__getitem__', '__setitem__', '__delitem__')
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_abc(self):
        self.assertIsInstance(OrderedDict(), MutableMapping)
        self.assertTrue(issubclass(OrderedDict, MutableMapping))
项目:srctools    作者:TeamSpen210    | 项目源码 | 文件源码
def test_EmptyMapping():
    marker = object()

    # It should be possible to 'construct' an instance..
    assert EmptyMapping() is EmptyMapping

    # Must be passable to dict()
    assert dict(EmptyMapping) == {}

    # EmptyMapping['x'] raises in various forms.
    assert 'x' not in EmptyMapping
    with pytest.raises(KeyError):
        EmptyMapping['x']
    with pytest.raises(KeyError):
        del EmptyMapping['x']

    EmptyMapping['x'] = 4  # Shouldn't fail

    assert 'x' not in EmptyMapping  # but it's a no-op
    with pytest.raises(KeyError):
        EmptyMapping['x']

    # Check it's all empty
    check_empty_iterable(EmptyMapping, 'EmptyMapping')
    check_empty_iterable(EmptyMapping.keys(), 'keys()')
    check_empty_iterable(EmptyMapping.values(), 'values()')
    check_empty_iterable(EmptyMapping.items(), 'items()', item=('x', 'y'))

    # Dict methods 
    assert EmptyMapping.get('x') is None
    assert EmptyMapping.setdefault('x') is None

    assert EmptyMapping.get('x', marker) is marker
    assert EmptyMapping.setdefault('x', marker) is marker
    assert EmptyMapping.pop('x', marker) is marker

    with pytest.raises(KeyError):
        EmptyMapping.popitem()
    with pytest.raises(KeyError):
        EmptyMapping.pop('x')

    assert not EmptyMapping

    assert len(EmptyMapping) == 0

    # Should work, but do nothing and return None.
    assert EmptyMapping.update({1: 23, 'test': 34, }) is None
    assert EmptyMapping.update(other=5, a=1, b=3) is None

    # Can't give more than one mapping as a positional argument,
    # though.
    with pytest.raises(TypeError):
        EmptyMapping.update({3: 4}, {1: 2})

    # Check it's registered in ABCs.
    from collections import abc
    assert isinstance(EmptyMapping, abc.Container)
    assert isinstance(EmptyMapping, abc.Sized)
    assert isinstance(EmptyMapping, abc.Mapping)
    assert isinstance(EmptyMapping, abc.MutableMapping)
项目:pypyr-cli    作者:pypyr    | 项目源码 | 文件源码
def test_context_is_dictionary_like():
    """Context should behave like a dictionary"""
    # initializes to empty
    d = Context()
    assert d is not None
    # len is not a given on custom implementations
    assert len(d) == 0

    # dict ctor "just works"
    d = Context({'k1': 'v1', 'k2': 'v2'})
    assert d
    assert len(d) == 2
    assert d['k1'] == 'v1'
    assert d['k2'] == 'v2'

    # __set_item__ assignment add and update works
    d['k1'] = 'value 1'
    d['k2'] = 'value 2'
    d['k3'] = ['one list', 'two list', 'three list']
    d['k4'] = {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': 'vv3'}
    d['k5'] = True
    d['k6'] = ('thing', False, ['1', '2', '3'], 6)
    d['k7'] = 77

    assert d['k5']

    # isinstance resolves to dict - this test might become invalid if refactor
    # to a MutableMapping custom object
    assert isinstance(d, dict)
    assert isinstance(d, MutableMapping)
    assert len(d) == 7

    # items() can iterate
    for k, v in d.items():
        if k == 'k4':
            assert isinstance(v, dict)

        if k == 'k6':
            assert isinstance(v, tuple)

    # values() can iterate
    for v in d.values():
        assert v

    # __get_item__ works
    assert d['k1'] == 'value 1'

    # update merging works
    mergedic = {'k1': 'NEWVALUE'}
    d.update(mergedic)
    assert d['k1'] == 'NEWVALUE'

    # del and clear
    original_length = len(d)
    del d['k1']
    assert 'k1' not in d
    assert len(d) == original_length - 1

    d.clear()
    assert len(d) == 0