本文整理汇总了Python中collections.MutableSequence方法的典型用法代码示例。如果您正苦于以下问题:Python collections.MutableSequence方法的具体用法?Python collections.MutableSequence怎么用?Python collections.MutableSequence使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections
的用法示例。
在下文中一共展示了collections.MutableSequence方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: floatify_latlng
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def floatify_latlng(input_value):
"""
Work around a JSON dict with string, not float, lat/lngs.
Given anything (list/dict/etc) it will return that thing again, *but* any
dict (at any level) that has only 2 elements lat & lng, will be replaced
with the lat & lng turned into floats.
If the API returns the lat/lng as strings, and not numbers, then this
function will 'clean them up' to be floats.
"""
if isinstance(input_value, collections.Mapping):
if len(input_value) == 2 and sorted(input_value.keys()) == ['lat', 'lng']:
# This dict has only 2 keys 'lat' & 'lon'
return {'lat': float_if_float(input_value["lat"]), 'lng': float_if_float(input_value["lng"])}
else:
return dict((key, floatify_latlng(value)) for key, value in input_value.items())
elif isinstance(input_value, collections.MutableSequence):
return [floatify_latlng(x) for x in input_value]
else:
return input_value
示例2: repr_list
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def repr_list(_list, indent):
"""Return a debug representation of a list or tuple."""
# pprint represents lists and tuples in one row if possible. We want one
# per row, so we iterate ourselves.
if _list is None:
return 'None'
if isinstance(_list, MutableSequence):
bm = '['
em = ']'
elif isinstance(_list, Iterable):
bm = '('
em = ')'
else:
raise TypeError("Object must be an iterable, but is a %s" %
type(_list))
ret = bm + '\n'
for value in _list:
ret += _indent('%r,\n' % value, 2)
ret += em
ret = repr_text(ret, indent=indent)
return ret.lstrip(' ')
示例3: _shell_join
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def _shell_join(seq):
"""
Convert a nested list of strings to a shell command.
Each string in the list is escaped as necessary to allow it to be
passed to a shell as a single word. If an item is a list, it is a
nested command, which will be escaped first, and then added as a
single word to the top-level command.
For example, ['su', 'root', '-c', ['apt-get', 'update']] becomes
"su root -c 'apt-get update'".
"""
result = []
for word in seq:
if isinstance(word, (tuple, MutableSequence)):
word = _shell_join(word)
escaped = shell_quote(word)
result.append(escaped)
return ' '.join(result)
示例4: translate_strings
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def translate_strings(self, strings, target_language, source_language='en', optimized=True):
assert isinstance(strings, collections.MutableSequence), \
'`strings` should be a sequence containing string_types'
assert not optimized, 'optimized=True is not supported in `GoogleAPITranslatorService`'
if len(strings) == 0:
return []
elif len(strings) <= self.max_segments:
setattr(self, 'translated_strings', getattr(self, 'translated_strings', []))
response = self.service.translations() \
.list(source=source_language, target=target_language, q=strings).execute()
self.translated_strings.extend([t.get('translatedText') for t in response.get('translations')])
return self.translated_strings
else:
self.translate_strings(strings[0:self.max_segments], target_language, source_language, optimized)
_translated_strings = self.translate_strings(strings[self.max_segments:],
target_language, source_language, optimized)
# reset the property or it will grow with subsequent calls
self.translated_strings = []
return _translated_strings
示例5: remove_key
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def remove_key(self, key):
# The parts of the ConfigSection that might contain "key"
trackers = [self.validation_methods,
self._destinations,
self._restricted,
self._required_keys,
self.defaults,
self._values,
self._unvalidated_keys,
]
for tracker in trackers:
if key in tracker:
if isinstance(tracker, collections.MutableMapping):
del tracker[key]
elif isinstance(tracker, collections.MutableSequence):
tracker.remove(key)
elif isinstance(tracker, collections.MutableSet):
tracker.discard(key)
示例6: test_collections_as_base
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def test_collections_as_base(self):
class M(collections.Mapping): ...
self.assertIsSubclass(M, typing.Mapping)
self.assertIsSubclass(M, typing.Iterable)
class S(collections.MutableSequence): ...
self.assertIsSubclass(S, typing.MutableSequence)
self.assertIsSubclass(S, typing.Iterable)
class I(collections.Iterable): ...
self.assertIsSubclass(I, typing.Iterable)
class A(collections.Mapping, metaclass=abc.ABCMeta): ...
class B: ...
A.register(B)
self.assertIsSubclass(B, typing.Mapping)
示例7: floatify_latlng
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def floatify_latlng(input_value):
"""
Work around a JSON dict with string, not float, lat/lngs.
Given anything (list/dict/etc) it will return that thing again, *but* any
dict (at any level) that has only 2 elements lat & lng, will be replaced
with the lat & lng turned into floats.
If the API returns the lat/lng as strings, and not numbers, then this
function will 'clean them up' to be floats.
"""
if isinstance(input_value, collections.Mapping):
if len(input_value) == 2 and sorted(input_value.keys()) == ['lat', 'lng']:
# This dict has only 2 keys 'lat' & 'lon'
return {'lat': float_if_float(input_value["lat"]), 'lng': float_if_float(input_value["lng"])}
else:
return dict((key, floatify_latlng(value)) for key, value in input_value.items())
elif isinstance(input_value, collections.MutableSequence):
return [floatify_latlng(x) for x in input_value]
else:
return input_value
示例8: remove
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def remove(self, pointer):
"""Remove element from sequence, member from mapping.
:param pointer: the path to search in
:return: resolved document
:rtype: Target
"""
doc = deepcopy(self.document)
parent, obj = None, doc
try:
# fetching
for token in Pointer(pointer):
parent, obj = obj, token.extract(obj, bypass_ref=True)
# removing
if isinstance(parent, Mapping):
del parent[token]
if isinstance(parent, MutableSequence):
parent.pop(int(token))
except Exception as error:
raise Error(*error.args)
return Target(doc)
示例9: modifies_known_mutable
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def modifies_known_mutable(obj, attr):
"""This function checks if an attribute on a builtin mutable object
(list, dict, set or deque) would modify it if called. It also supports
the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
with Python 2.6 onwards the abstract base classes `MutableSet`,
`MutableMapping`, and `MutableSequence`.
>>> modifies_known_mutable({}, "clear")
True
>>> modifies_known_mutable({}, "keys")
False
>>> modifies_known_mutable([], "append")
True
>>> modifies_known_mutable([], "index")
False
If called with an unsupported object (such as unicode) `False` is
returned.
>>> modifies_known_mutable("foo", "upper")
False
"""
for typespec, unsafe in _mutable_spec:
if isinstance(obj, typespec):
return attr in unsafe
return False
示例10: testRepeatedFieldsAreSequences
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def testRepeatedFieldsAreSequences(self, message_module):
m = message_module.TestAllTypes()
self.assertIsInstance(m.repeated_int32, collections.MutableSequence)
self.assertIsInstance(m.repeated_nested_message,
collections.MutableSequence)
示例11: test_MutableSequence
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def test_MutableSequence(self):
for sample in [tuple, str]:
self.assertNotIsInstance(sample(), MutableSequence)
self.assertFalse(issubclass(sample, MutableSequence))
for sample in [list]:
self.assertIsInstance(sample(), MutableSequence)
self.assertTrue(issubclass(sample, MutableSequence))
self.assertFalse(issubclass(basestring, MutableSequence))
self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
'__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
示例12: _transform_list
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def _transform_list(self, model, params, transformation, target_shape):
if not isinstance(params, MutableSequence):
return
member_model = model.member
member_shape = member_model.name
for i, item in enumerate(params):
if member_shape == target_shape:
params[i] = transformation(item)
else:
self._transform_parameters(
member_model, params[i], transformation, target_shape)
示例13: __set__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def __set__(self, instance, value):
if isinstance(value, collections.MutableSequence):
value = self._resolve(value)
if value is None:
value = []
super().__set__(instance, value)
示例14: validate
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def validate(self, value):
if not value:
return
if not isinstance(value, collections.MutableSequence):
raise InvalidModelFieldError("should be a list")
for i in value:
for validator in self.validators:
validator(i)
示例15: _deserialize
# 需要导入模块: import collections [as 别名]
# 或者: from collections import MutableSequence [as 别名]
def _deserialize(self, value, attr, obj, recurse_lvl=0):
"""
Check deeply to see if there is a {'bytes': [...]} dict and if so
convert it to a bytes object
"""
if recurse_lvl == 0:
valued = super(EntriesField, self)._deserialize(value, attr, obj)
else:
valued = value
if isinstance(valued, MutableMapping):
for key in six.iterkeys(valued):
if key == self._BYTES_KEY:
return self._hex_list_to_binary(valued[key])
valued[key] = self._deserialize(
value=valued[key],
attr=attr,
obj=obj,
recurse_lvl=(recurse_lvl + 1),
)
return valued
if isinstance(valued, MutableSequence):
for i in range(len(valued)):
valued[i] = self._deserialize(
value=valued[i],
attr=attr,
obj=obj,
recurse_lvl=(recurse_lvl + 1),
)
return valued
return valued