本文整理匯總了Python中collections.abc.MutableMapping方法的典型用法代碼示例。如果您正苦於以下問題:Python abc.MutableMapping方法的具體用法?Python abc.MutableMapping怎麽用?Python abc.MutableMapping使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類collections.abc
的用法示例。
在下文中一共展示了abc.MutableMapping方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: attributes
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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
示例2: set_attribute
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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)
示例3: write_zarr
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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)
示例4: __getitem__
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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
示例5: test_abc_bases
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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)
示例6: test_subclassing_register
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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)
示例7: __init__
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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"]
)
示例8: __init__
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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"]
)
示例9: from_rtm
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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)
示例10: get_parsed_context
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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
示例11: addConvenienceForBasicMapping
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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)
示例12: __init__
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
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.")
示例13: enable_connect_protocol
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
def enable_connect_protocol(self, value):
self[SettingCodes.ENABLE_CONNECT_PROTOCOL] = value
# Implement the MutableMapping API.
示例14: get_context
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
def get_context(self, request):
context = (
copy.copy(self.context)
if self.context and isinstance(self.context, MutableMapping)
else {}
)
if isinstance(context, MutableMapping) and "request" not in context:
context.update({"request": request})
return context
示例15: __call__
# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import MutableMapping [as 別名]
def __call__(self, series, dtype):
if dtype is None:
inferred_dtype = None
if callable(self._arg):
# arg is a function, try to inspect the signature
sig = inspect.signature(self._arg)
return_type = sig.return_annotation
if return_type is not inspect._empty:
inferred_dtype = np.dtype(return_type)
else:
if isinstance(self._arg, MutableMapping):
inferred_dtype = pd.Series(self._arg).dtype
else:
inferred_dtype = self._arg.dtype
if inferred_dtype is not None and np.issubdtype(inferred_dtype, np.number):
if np.issubdtype(inferred_dtype, np.inexact):
# for the inexact e.g. float
# we can make the decision,
# but for int, due to the nan which may occur,
# we cannot infer the dtype
dtype = inferred_dtype
else:
dtype = inferred_dtype
if dtype is None:
raise ValueError('cannot infer dtype, '
'it needs to be specified manually for `map`')
else:
dtype = np.int64 if dtype is int else dtype
dtype = np.dtype(dtype)
inputs = [series]
if isinstance(self._arg, SERIES_TYPE):
inputs.append(self._arg)
return self.new_series(inputs, shape=series.shape, dtype=dtype,
index_value=series.index_value, name=series.name)