Python collections.MutableSequence() Examples
The following are 30
code examples of collections.MutableSequence().
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
, or try the search function
.
Example #1
Source File: geocoder.py From python-opencage-geocoder with MIT License | 6 votes |
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
Example #2
Source File: _utils.py From python-zhmcclient with Apache License 2.0 | 6 votes |
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(' ')
Example #3
Source File: bases.py From json-spec with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #4
Source File: _model.py From flocker with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: opencage.py From harpoon with GNU General Public License v3.0 | 6 votes |
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
Example #6
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
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)
Example #7
Source File: services.py From django-autotranslate with MIT License | 6 votes |
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
Example #8
Source File: config.py From virt-who with GNU General Public License v2.0 | 6 votes |
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)
Example #9
Source File: test_collections.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
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')
Example #10
Source File: sandbox.py From luci-py with Apache License 2.0 | 5 votes |
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
Example #11
Source File: util.py From panel with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #12
Source File: translation.py From mochi with MIT License | 5 votes |
def translate_loaded_file(self, filename, show_tokens=False): body = [] self.filename = filename with open(filename, 'r') as f: sexps = parse(lex(f.read(), debug=show_tokens), filename) for sexp in sexps: if isinstance(sexp, MutableSequence): sexp = tuple_it(sexp) if sexp is COMMENT: continue pre, value = self.translate(sexp) body.extend(pre) body.append(value) return body
Example #13
Source File: builtins.py From mochi with MIT License | 5 votes |
def tuple_it(obj): return tuple(map(tuple_it, obj)) if isinstance(obj, MutableSequence) else obj
Example #14
Source File: builtins.py From mochi with MIT License | 5 votes |
def eval_tokens(tokens, globals=global_env, locals=None): sexps = parse(tokens.__iter__()) for sexp in sexps: if isinstance(sexp, MutableSequence): sexp = tuple_it(sexp) if sexp is COMMENT: continue py_ast = translator.translate_sexp_to_interact(sexp) if py_ast is not None: code = compile(py_ast, '<string>', 'exec') if code is not None: exec(code, globals, locals)
Example #15
Source File: translation.py From mochi with MIT License | 5 votes |
def tuple_it(obj): return tuple(map(tuple_it, obj)) if isinstance(obj, MutableSequence) else obj #---
Example #16
Source File: translation.py From mochi with MIT License | 5 votes |
def translate_block(self, mochi_block, filename='<string>', show_tokens=False): """Translate sexpressions into a Python AST. """ sexps = parse(lex(mochi_block, debug=show_tokens), filename) body = [] for sexp in sexps: if isinstance(sexp, MutableSequence): sexp = tuple_it(sexp) if sexp is COMMENT: continue pre, value = self.translate(sexp) body.extend([self.enclose(exp, True) for exp in pre]) body.append(self.enclose(value, True)) return ast.Module(body=body)
Example #17
Source File: bases.py From json-spec with BSD 3-Clause "New" or "Revised" License | 5 votes |
def replace(self, pointer, value): """Replace element from sequence, member from mapping. :param pointer: the path to search in :param value: the new value :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) # replace value = deepcopy(value) if isinstance(parent, Mapping): parent[token] = value if isinstance(parent, MutableSequence): parent[int(token)] = value except Exception as error: raise Error(*error.args) return Target(doc)
Example #18
Source File: json2xls.py From json2xls with BSD 2-Clause "Simplified" License | 5 votes |
def flatten(self, data_dict, parent_key='', sep='.'): '''对套嵌的dict进行flatten处理为单层dict :param dict data_dict: 需要处理的dict数据。 :param str parent_key: 上层字典的key,默认为空字符串。 :param str sep: 套嵌key flatten后的分割符, 默认为“.” 。 ''' out = {} def _flatten(x, parent_key, sep): if isinstance(x, collections.MutableMapping): for a in x: _flatten(x[a], parent_key + a + sep, sep) elif isinstance(x, collections.MutableSequence): i = 0 for a in x: _flatten(a, parent_key + str(i) + sep, sep) i += 1 else: if not isinstance(x, ("".__class__, u"".__class__)): x = str(x) out[parent_key[:-1].encode('utf-8')] = x _flatten(data_dict, parent_key, sep) return OrderedDict(out)
Example #19
Source File: sandbox.py From luci-py with Apache License 2.0 | 5 votes |
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
Example #20
Source File: sandbox.py From Financial-Portfolio-Flask with MIT License | 5 votes |
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
Example #21
Source File: sandbox.py From luci-py with Apache License 2.0 | 5 votes |
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
Example #22
Source File: sandbox.py From luci-py with Apache License 2.0 | 5 votes |
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
Example #23
Source File: sandbox.py From luci-py with Apache License 2.0 | 5 votes |
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
Example #24
Source File: transform.py From aws-extender with MIT License | 5 votes |
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)
Example #25
Source File: Alert.py From wavectl with Apache License 2.0 | 5 votes |
def _formatValueForSummaryTable(k, v, enableColor): """Format the given value for a nice print in the summary table """ if isinstance(v, collections.MutableSequence): return " ".join([Alert._maybeColor(k, x, enableColor) for x in v]) else: return Alert._maybeColor(k, v, enableColor)
Example #26
Source File: sandbox.py From planespotter with MIT License | 5 votes |
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
Example #27
Source File: transform.py From AWS-Transit-Gateway-Demo-MultiAccount with MIT License | 5 votes |
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)
Example #28
Source File: transform.py From AWS-Transit-Gateway-Demo-MultiAccount with MIT License | 5 votes |
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)
Example #29
Source File: sandbox.py From Flask-P2P with MIT License | 5 votes |
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
Example #30
Source File: message_test.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
def testRepeatedFieldsAreSequences(self, message_module): m = message_module.TestAllTypes() self.assertIsInstance(m.repeated_int32, collections.MutableSequence) self.assertIsInstance(m.repeated_nested_message, collections.MutableSequence)