Python collections.abc.MutableMapping() Examples

The following are 30 code examples of collections.abc.MutableMapping(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module collections.abc , or try the search function .
Example #1
Source File: names.py    From python-gssapi with ISC License 7 votes vote down vote up
def attributes(self):
        """The attributes of this name (:requires-ext:`rfc6680`)

        The attributes are presenting in the form of a
        :class:`~collections.MutableMapping` (a dict-like object).

        Retrieved values will always be in the form of :class:`frozensets`.

        When assigning values, if iterables are used, they be considered to be
        the set of values for the given attribute.  If a non-iterable is used,
        it will be considered a single value, and automatically wrapped in an
        iterable.

        Note:
            String types (includes :class:`bytes`) are not considered to
            be iterables in this case.
        """
        if self._attr_obj is None:
            raise NotImplementedError("Your GSSAPI implementation does not "
                                      "support RFC 6680 (the GSSAPI naming "
                                      "extensions)")

        return self._attr_obj 
Example #2
Source File: zarr.py    From anndata with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write_zarr(
    store: Union[MutableMapping, str, Path],
    adata: AnnData,
    chunks=None,
    **dataset_kwargs,
) -> None:
    if isinstance(store, Path):
        store = str(store)
    adata.strings_to_categoricals()
    if adata.raw is not None:
        adata.strings_to_categoricals(adata.raw.var)
    f = zarr.open(store, mode="w")
    if chunks is not None and not isinstance(adata.X, sparse.spmatrix):
        write_attribute(f, "X", adata.X, dict(chunks=chunks, **dataset_kwargs))
    else:
        write_attribute(f, "X", adata.X, dataset_kwargs)
    write_attribute(f, "obs", adata.obs, dataset_kwargs)
    write_attribute(f, "var", adata.var, dataset_kwargs)
    write_attribute(f, "obsm", adata.obsm, dataset_kwargs)
    write_attribute(f, "varm", adata.varm, dataset_kwargs)
    write_attribute(f, "obsp", adata.obsp, dataset_kwargs)
    write_attribute(f, "varp", adata.varp, dataset_kwargs)
    write_attribute(f, "layers", adata.layers, dataset_kwargs)
    write_attribute(f, "uns", adata.uns, dataset_kwargs)
    write_attribute(f, "raw", adata.raw, dataset_kwargs) 
Example #3
Source File: _convenience_mapping.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 6 votes vote down vote up
def addConvenienceForBasicMapping(classname, readonly=True):
    """
    Add the convience methods for a Cocoa mapping type

    Used to add the basic collections.abc.Mapping or collections.abc.MutableMapping
    APIs to a Cocoa class that has an API simular to NSDictionary.
    """
    addConvenienceForClass(
        classname, _CONVENIENCES_MAPPING_RO if readonly else _CONVENIENCES_MAPPING_RW
    )

    try:
        lst = CLASS_ABC[classname]
    except KeyError:
        lst = CLASS_ABC[classname] = []

    lst.append(collections_abc.Mapping if readonly else collections_abc.MutableMapping) 
Example #4
Source File: yamlfile.py    From pypyr-cli with Apache License 2.0 6 votes vote down vote up
def get_parsed_context(args):
    """Parse input as path to a yaml file, returns context as dictionary."""
    assert args, ("pipeline must be invoked with context arg set. For "
                  "this yaml parser you're looking for something "
                  "like: "
                  "pypyr pipelinename './myyamlfile.yaml'")
    logger.debug("starting")
    path = ' '.join(args)
    logger.debug("attempting to open file: %s", path)
    with open(path) as yaml_file:
        yaml_loader = yaml.YAML(typ='safe', pure=True)
        payload = yaml_loader.load(yaml_file)

    logger.debug("yaml file parsed. Count: %d", 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 
Example #5
Source File: events.py    From slack-sansio with MIT License 6 votes vote down vote up
def from_rtm(cls, raw_event: MutableMapping) -> "Event":
        """
        Create an event with data coming from the RTM API.

        If the event type is a message a :class:`slack.events.Message` is returned.

        Args:
            raw_event: JSON decoded data from the RTM API

        Returns:
            :class:`slack.events.Event` or :class:`slack.events.Message`
        """
        if raw_event["type"].startswith("message"):
            return Message(raw_event)
        else:
            return Event(raw_event) 
Example #6
Source File: commands.py    From slack-sansio with MIT License 6 votes vote down vote up
def __init__(
        self,
        raw_command: typing.MutableMapping,
        verification_token: Optional[str] = None,
        team_id: Optional[str] = None,
    ) -> None:
        self.command = raw_command

        if verification_token and self.command["token"] != verification_token:
            raise exceptions.FailedVerification(
                self.command["token"], self.command["team_id"]
            )

        if team_id and self.command["team_id"] != team_id:
            raise exceptions.FailedVerification(
                self.command["token"], self.command["team_id"]
            ) 
Example #7
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_subclassing_register(self):

        class A(typing.Container): ...
        class B(A): ...

        class C: ...
        A.register(C)
        self.assertIsSubclass(C, A)
        self.assertNotIsSubclass(C, B)

        class D: ...
        B.register(D)
        self.assertIsSubclass(D, A)
        self.assertIsSubclass(D, B)

        class M(): ...
        collections.MutableMapping.register(M)
        self.assertIsSubclass(M, typing.Mapping) 
Example #8
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_abc_bases(self):
        class MM(MutableMapping[str, str]):
            def __getitem__(self, k):
                return None
            def __setitem__(self, k, v):
                pass
            def __delitem__(self, k):
                pass
            def __iter__(self):
                return iter(())
            def __len__(self):
                return 0
        # this should just work
        MM().update()
        self.assertIsInstance(MM(), collections_abc.MutableMapping)
        self.assertIsInstance(MM(), MutableMapping)
        self.assertNotIsInstance(MM(), List)
        self.assertNotIsInstance({}, MM) 
Example #9
Source File: actions.py    From slack-sansio with MIT License 6 votes vote down vote up
def __init__(
        self,
        raw_action: typing.MutableMapping,
        verification_token: Optional[str] = None,
        team_id: Optional[str] = None,
    ) -> None:
        self.action = raw_action

        if verification_token and self.action["token"] != verification_token:
            raise exceptions.FailedVerification(
                self.action["token"], self.action["team"]["id"]
            )

        if team_id and self.action["team"]["id"] != team_id:
            raise exceptions.FailedVerification(
                self.action["token"], self.action["team"]["id"]
            ) 
Example #10
Source File: chained_db.py    From regolith with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def __getitem__(self, key):
        res = None
        results = []
        # Try to get all the data from all the mappings
        for mapping in self.maps:
            results.append(mapping.get(key, Singleton))
        # if all the results are mapping create a ChainDB
        if all([isinstance(result, MutableMapping) for result in results]):
            for result in results:
                if res is None:
                    res = ChainDB(result)
                else:
                    res.maps.append(result)
        elif all([isinstance(result, list) for result in results]):
            return list(itertools.chain(*results))
        else:
            for result in reversed(results):
                if result is not Singleton:
                    return result
            raise KeyError("{} is none of the current mappings".format(key))
        return res 
Example #11
Source File: serializers.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_attribute(self, obj, attr, value):
        """Set value of attribute in given object instance.

        Reason for existence of this method is the fact that 'attribute' can
        be also a object's key if it is a dict or any other kind of mapping.

        Args:
            obj (object): object instance to modify
            attr (str): attribute (or key) to change
            value: value to set

        """
        # if this is any mutable mapping then instead of attributes use keys
        if isinstance(obj, MutableMapping):
            obj[attr] = value
        else:
            setattr(obj, attr, value) 
Example #12
Source File: events.py    From slack-sansio with MIT License 5 votes vote down vote up
def __init__(
        self,
        msg: Optional[MutableMapping] = None,
        metadata: Optional[MutableMapping] = None,
    ) -> None:
        if not msg:
            msg = {}
        super().__init__(msg, metadata) 
Example #13
Source File: test_collections.py    From android_universal with MIT License 5 votes vote down vote up
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__') 
Example #14
Source File: test_ordered_dict.py    From android_universal with MIT License 5 votes vote down vote up
def test_abc(self):
        OrderedDict = self.OrderedDict
        self.assertIsInstance(OrderedDict(), MutableMapping)
        self.assertTrue(issubclass(OrderedDict, MutableMapping)) 
Example #15
Source File: bottle.py    From slack-machine with MIT License 5 votes vote down vote up
def view(tpl_name, **defaults):
    """ Decorator: renders a template for a handler.
        The handler can control its behavior like that:

          - return a dict of template vars to fill out the template
          - return something other than a dict and the view decorator will not
            process the template, but return the handler result as is.
            This includes returning a HTTPResponse(dict) to get,
            for instance, JSON with autojson or other castfilters.
    """

    def decorator(func):

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            if isinstance(result, (dict, DictMixin)):
                tplvars = defaults.copy()
                tplvars.update(result)
                return template(tpl_name, **tplvars)
            elif result is None:
                return template(tpl_name, defaults)
            return result

        return wrapper

    return decorator 
Example #16
Source File: actions.py    From slack-sansio with MIT License 5 votes vote down vote up
def from_http(
        cls,
        payload: typing.MutableMapping,
        verification_token: Optional[str] = None,
        team_id: Optional[str] = None,
    ) -> "Action":
        action = json.loads(payload["payload"])
        return cls(action, verification_token=verification_token, team_id=team_id) 
Example #17
Source File: test_ordereddict.py    From cyordereddict with MIT License 5 votes vote down vote up
def test_abc(self):
        self.assertIsInstance(OrderedDict(), MutableMapping)
        self.assertTrue(issubclass(OrderedDict, MutableMapping)) 
Example #18
Source File: events.py    From slack-sansio with MIT License 5 votes vote down vote up
def __init__(
        self, raw_event: MutableMapping, metadata: Optional[MutableMapping] = None
    ) -> None:
        self.event = raw_event
        self.metadata = metadata 
Example #19
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_dict_subclass(self):

        class MyDict(typing.Dict[str, int]):
            pass

        d = MyDict()
        self.assertIsInstance(d, MyDict)
        self.assertIsInstance(d, typing.MutableMapping)

        self.assertIsSubclass(MyDict, dict)
        self.assertNotIsSubclass(dict, MyDict) 
Example #20
Source File: test_ordered_dict.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_abc(self):
        OrderedDict = self.OrderedDict
        self.assertIsInstance(OrderedDict(), MutableMapping)
        self.assertTrue(issubclass(OrderedDict, MutableMapping)) 
Example #21
Source File: util.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hashable(x):
    if isinstance(x, MutableSequence):
        return tuple(x)
    elif isinstance(x, MutableMapping):
        return tuple([(k,v) for k,v in x.items()])
    else:
        return x 
Example #22
Source File: model.py    From operator with Apache License 2.0 5 votes vote down vote up
def __getitem__(self, key):
        return self._data[key]


# We mix in MutableMapping here to get some convenience implementations, but whether it's actually
# mutable or not is controlled by the flag. 
Example #23
Source File: conf.py    From regolith with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def build_schema_doc(key):
    fn = "collections/" + key + ".rst"
    with open(fn, "w") as f:
        s = ""
        s += key.title() + "\n"
        s += "=" * len(key) + "\n"
        s += SCHEMAS[key]["_description"]["description"] + "\n\n"
        s += "Schema\n------\nThe following lists key names mapped to its " "type and meaning for each entry.\n\n"
        schema = SCHEMAS[key]
        schema_list = list(schema.keys())
        schema_list.sort()
        for k in schema_list:
            if k not in ["_description"]:
                s += format_key(schema[k], key=k)
        s += "\n\n"
        s += "YAML Example\n------------\n\n"
        s += ".. code-block:: yaml\n\n"
        temp = tempfile.NamedTemporaryFile()
        temp2 = tempfile.NamedTemporaryFile()
        documents = EXEMPLARS[key]
        if isinstance(documents, MutableMapping):
            documents = [documents]
        documents = {doc["_id"]: doc for doc in documents}
        dump_json(temp.name, documents)
        docs = sorted(documents.values(), key=_id_key)
        lines = [
            json.dumps(doc, sort_keys=True, indent=4, separators=(",", ": "))
            for doc in docs
        ]
        jd = "\n".join(lines)
        json_to_yaml(temp.name, temp2.name)
        with open(temp2.name, "r") as ff:
            s += indent(ff.read(), "\t")
        s += "\n\n"
        s += "JSON/Mongo Example\n------------------\n\n"
        s += ".. code-block:: json\n\n"
        s += indent(jd, "\t")
        s += "\n"
        f.write(s) 
Example #24
Source File: items.py    From ant_nest with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_value(item: Item, key: str) -> typing.Any:
    try:
        if isinstance(item, MutableMapping):
            return item[key]
        else:
            return getattr(item, key)
    except (KeyError, AttributeError) as e:
        raise ItemGetValueError from e 
Example #25
Source File: items.py    From ant_nest with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_value(item: Item, key: str, value: typing.Any):
    if isinstance(item, MutableMapping):
        item[key] = value
    else:
        setattr(item, key, value) 
Example #26
Source File: misc.py    From mriqc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _flatten(in_dict, parent_key="", sep="_"):
    items = []
    for k, val in list(in_dict.items()):
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(val, MutableMapping):
            items.extend(list(_flatten(val, new_key, sep=sep).items()))
        else:
            items.append((new_key, val))
    return dict(items) 
Example #27
Source File: api.py    From mutatest with MIT License 5 votes vote down vote up
def __init__(self, source_location: Optional[Union[str, Path]] = None) -> None:
        """Initialize the GenomeGroup.

        GenomeGroup is a MutableMapping collection of Genomes with defined ``source_file``
        locations. You can use it to apply standard filters or coverage files across the group and
        get all mutation targets for the group. Folders and files can be added through methods.

        Args:
            source_location: an optional folder for initialization using the default settings
                of no file exclusions except 'test' files. For more flexibility, initialize
                the class and then use the ``.add_folder()`` method directly.
        """

        # internal mapping for Genomes, not designed for direct modification, use class properties
        self._store: Dict[Path, Genome] = dict()

        if source_location is not None:
            source_location = Path(source_location)

            if source_location.is_dir():
                self.add_folder(source_location)

            elif source_location.is_file():
                self.add_file(source_location)

            else:
                raise TypeError(f"{source_location} is not a folder or file.") 
Example #28
Source File: model.py    From operator with Apache License 2.0 5 votes vote down vote up
def __getitem__(self, key):
        return self._data[key]


# We mix in MutableMapping here to get some convenience implementations, but whether it's actually
# mutable or not is controlled by the flag. 
Example #29
Source File: zarr.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_zarr(store: Union[str, Path, MutableMapping, zarr.Group]) -> AnnData:
    """\
    Read from a hierarchical Zarr array store.

    Parameters
    ----------
    store
        The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class.
    """
    if isinstance(store, Path):
        store = str(store)

    f = zarr.open(store, mode="r")
    d = {}
    for k in f.keys():
        # Backwards compat
        if k.startswith("raw."):
            continue
        if k in {"obs", "var"}:
            d[k] = read_dataframe(f[k])
        else:  # Base case
            d[k] = read_attribute(f[k])

    d["raw"] = _read_legacy_raw(f, d.get("raw"), read_dataframe, read_attribute)

    _clean_uns(d)

    return AnnData(**d) 
Example #30
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_union_compare_other(self):
        self.assertNotEqual(Union, object)
        self.assertNotEqual(Union, Any)
        self.assertNotEqual(ClassVar, Union)
        self.assertNotEqual(Optional, Union)
        self.assertNotEqual([None], Optional)
        self.assertNotEqual(Optional, typing.Mapping)
        self.assertNotEqual(Optional[typing.MutableMapping], Union)