我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.setitem()。
def decompile(self, data, ttFont): self.getGlyphName = ttFont.getGlyphName # for use in get/set item functions, for access by GID self.majorVersion, self.minorVersion, self.defaultVertOriginY, self.numVertOriginYMetrics = struct.unpack(">HHhH", data[:8]) assert (self.majorVersion <= 1), "Major version of VORG table is higher than I know how to handle" data = data[8:] vids = [] gids = [] pos = 0 for i in range(self.numVertOriginYMetrics): gid, vOrigin = struct.unpack(">Hh", data[pos:pos+4]) pos += 4 gids.append(gid) vids.append(vOrigin) self.VOriginRecords = vOrig = {} glyphOrder = ttFont.getGlyphOrder() try: names = map(operator.getitem, [glyphOrder]*self.numVertOriginYMetrics, gids) except IndexError: getGlyphName = self.getGlyphName names = map(getGlyphName, gids ) list(map(operator.setitem, [vOrig]*self.numVertOriginYMetrics, names, vids))
def postRead(self, rawTable, font): mapping = {} input = _getGlyphsFromCoverageTable(rawTable["Coverage"]) lenMapping = len(input) if self.Format == 1: delta = rawTable["DeltaGlyphID"] inputGIDS = [ font.getGlyphID(name) for name in input ] outGIDS = [ (glyphID + delta) % 65536 for glyphID in inputGIDS ] outNames = [ font.getGlyphName(glyphID) for glyphID in outGIDS ] list(map(operator.setitem, [mapping]*lenMapping, input, outNames)) elif self.Format == 2: assert len(input) == rawTable["GlyphCount"], \ "invalid SingleSubstFormat2 table" subst = rawTable["Substitute"] list(map(operator.setitem, [mapping]*lenMapping, input, subst)) else: assert 0, "unknown format: %s" % self.Format self.mapping = mapping
def fromXML(self, name, attrs, content, ttFont): if not hasattr(self, "ColorLayers"): self.ColorLayers = {} self.getGlyphName = ttFont.getGlyphName # for use in get/set item functions, for access by GID if name == "ColorGlyph": glyphName = attrs["name"] for element in content: if isinstance(element, basestring): continue layers = [] for element in content: if isinstance(element, basestring): continue layer = LayerRecord() layer.fromXML(element[0], element[1], element[2], ttFont) layers.append (layer) operator.setitem(self, glyphName, layers) elif "value" in attrs: setattr(self, name, safeEval(attrs["value"]))
def process_swagger(spec): spec = add_custom_objects_spec(spec) apply_func_to_spec_operations(spec, strip_tags_from_operation_id) operation_ids = {} apply_func_to_spec_operations(spec, lambda op, _: operator.setitem( operation_ids, op['operationId'], op)) try: apply_func_to_spec_operations( spec, remove_watch_operations, operation_ids) except PreprocessingException as e: print(e.message) remove_model_prefixes(spec, 'io.k8s') inline_primitive_models(spec) return spec
def test_setslice_partial_wrong_length(self): Element = self.Element root = Element("root") l = ["c1", "c2", "c3", "c4"] root.c = l self.assertEqual(["c1", "c2", "c3", "c4"], [ c.text for c in root.c ]) self.assertEqual(l, [ c.text for c in root.c ]) new_slice = ["cA", "cB", "cC"] self.assertRaises( ValueError, operator.setitem, l, slice(1,2,-1), new_slice) self.assertRaises( ValueError, operator.setitem, root.c, slice(1,2,-1), new_slice)
def testTopLevelExtensionsForOptionalMessage(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.optional_foreign_message_extension self.assertTrue(not extendee_proto.HasExtension(extension)) self.assertEqual(0, extendee_proto.Extensions[extension].c) # As with normal (non-extension) fields, merely reading from the # thing shouldn't set the "has" bit. self.assertTrue(not extendee_proto.HasExtension(extension)) extendee_proto.Extensions[extension].c = 23 self.assertEqual(23, extendee_proto.Extensions[extension].c) self.assertTrue(extendee_proto.HasExtension(extension)) # Save a reference here. foreign_message = extendee_proto.Extensions[extension] extendee_proto.ClearExtension(extension) self.assertTrue(foreign_message is not extendee_proto.Extensions[extension]) # Setting a field on foreign_message now shouldn't set # any "has" bits on extendee_proto. foreign_message.c = 42 self.assertEqual(42, foreign_message.c) self.assertTrue(foreign_message.HasField('c')) self.assertTrue(not extendee_proto.HasExtension(extension)) # Shouldn't be allowed to do Extensions[extension] = 'a' self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions, extension, 'a')
def testTopLevelExtensionsForRepeatedMessage(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.repeatedgroup_extension self.assertEqual(0, len(extendee_proto.Extensions[extension])) group = extendee_proto.Extensions[extension].add() group.a = 23 self.assertEqual(23, extendee_proto.Extensions[extension][0].a) group.a = 42 self.assertEqual(42, extendee_proto.Extensions[extension][0].a) group_list = extendee_proto.Extensions[extension] extendee_proto.ClearExtension(extension) self.assertEqual(0, len(extendee_proto.Extensions[extension])) self.assertTrue(group_list is not extendee_proto.Extensions[extension]) # Shouldn't be allowed to do Extensions[extension] = 'a' self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions, extension, 'a')
def test_chaindict(): d = reactive.ReactiveChainMap() dd = d.new_child() sink = dd.all.sink() sink.start() struct_sink = dd.structure.sink() struct_sink.start() d['foo'] = 'bar' dd['foo'] = 'zoo' d['foo'] = 'coo' assert dd['foo'] == 'zoo' sink_res = [((operator.setitem, (dd, 'foo', 'bar')),), ((operator.setitem, (dd, 'foo', 'bar')),), ((operator.setitem, (dd, 'foo', 'zoo')),), ((operator.setitem, (dd, 'foo', 'zoo')),),] assert list(sink) == sink_res assert list(sink)[0][0][1][0] is dd
def number_of_args(fn): """Return the number of positional arguments for a function, or None if the number is variable. Looks inside any decorated functions.""" try: if hasattr(fn, '__wrapped__'): return number_of_args(fn.__wrapped__) if any(p.kind == p.VAR_POSITIONAL for p in signature(fn).parameters.values()): return None else: return sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in signature(fn).parameters.values()) except ValueError: # signatures don't work for built-in operators, so check for a few explicitly UNARY_OPS = [len, op.not_, op.truth, op.abs, op.index, op.inv, op.invert, op.neg, op.pos] BINARY_OPS = [op.lt, op.le, op.gt, op.ge, op.eq, op.ne, op.is_, op.is_not, op.add, op.and_, op.floordiv, op.lshift, op.mod, op.mul, op.or_, op.pow, op.rshift, op.sub, op.truediv, op.xor, op.concat, op.contains, op.countOf, op.delitem, op.getitem, op.indexOf] TERNARY_OPS = [op.setitem] if fn in UNARY_OPS: return 1 elif fn in BINARY_OPS: return 2 elif fn in TERNARY_OPS: return 3 else: raise NotImplementedError("Bult-in operator {} not supported".format(fn))
def test_check_closed(self): f = dumbdbm.open(_fname, 'c') f.close() for meth in (partial(operator.delitem, f), partial(operator.setitem, f, 'b'), partial(operator.getitem, f), partial(operator.contains, f)): with self.assertRaises(dumbdbm.error) as cm: meth('test') self.assertEqual(str(cm.exception), "DBM object has already been closed") for meth in (operator.methodcaller('keys'), operator.methodcaller('iterkeys'), operator.methodcaller('items'), len): with self.assertRaises(dumbdbm.error) as cm: meth(f) self.assertEqual(str(cm.exception), "DBM object has already been closed")
def setUp(self): """ Patch the L{ls} module's time function so the results of L{lsLine} are deterministic. """ self.now = 123456789 def fakeTime(): return self.now self.patch(ls, 'time', fakeTime) # Make sure that the timezone ends up the same after these tests as # it was before. if 'TZ' in os.environ: self.addCleanup(operator.setitem, os.environ, 'TZ', os.environ['TZ']) self.addCleanup(time.tzset) else: def cleanup(): # os.environ.pop is broken! Don't use it! Ever! Or die! try: del os.environ['TZ'] except KeyError: pass time.tzset() self.addCleanup(cleanup)
def decompile(self, data, ttFont): self.getGlyphName = ttFont.getGlyphName # for use in get/set item functions, for access by GID self.version, numBaseGlyphRecords, offsetBaseGlyphRecord, offsetLayerRecord, numLayerRecords = struct.unpack(">HHLLH", data[:14]) assert (self.version == 0), "Version of COLR table is higher than I know how to handle" glyphOrder = ttFont.getGlyphOrder() gids = [] layerLists = [] glyphPos = offsetBaseGlyphRecord for i in range(numBaseGlyphRecords): gid, firstLayerIndex, numLayers = struct.unpack(">HHH", data[glyphPos:glyphPos+6]) glyphPos += 6 gids.append(gid) assert (firstLayerIndex + numLayers <= numLayerRecords) layerPos = offsetLayerRecord + firstLayerIndex * 4 layers = [] for j in range(numLayers): layerGid, colorID = struct.unpack(">HH", data[layerPos:layerPos+4]) try: layerName = glyphOrder[layerGid] except IndexError: layerName = self.getGlyphName(layerGid) layerPos += 4 layers.append(LayerRecord(layerName, colorID)) layerLists.append(layers) self.ColorLayers = colorLayerLists = {} try: names = list(map(operator.getitem, [glyphOrder]*numBaseGlyphRecords, gids)) except IndexError: getGlyphName = self.getGlyphName names = list(map(getGlyphName, gids )) list(map(operator.setitem, [colorLayerLists]*numBaseGlyphRecords, names, layerLists))
def parseFeatureList(lines, lookupMap=None, featureMap=None): self = ot.FeatureList() self.FeatureRecord = [] with lines.between('feature table'): for line in lines: name, featureTag, lookups = line if featureMap is not None: assert name not in featureMap, "Duplicate feature name: %s" % name featureMap[name] = len(self.FeatureRecord) # If feature name is integer, make sure it matches its index. try: assert int(name) == len(self.FeatureRecord), "%d %d" % (name, len(self.FeatureRecord)) except ValueError: pass featureRec = ot.FeatureRecord() featureRec.FeatureTag = featureTag featureRec.Feature = ot.Feature() self.FeatureRecord.append(featureRec) feature = featureRec.Feature feature.FeatureParams = None syms = stripSplitComma(lookups) feature.LookupListIndex = theList = [None] * len(syms) for i,sym in enumerate(syms): setReference(mapLookup, lookupMap, sym, setitem, theList, i) feature.LookupCount = len(feature.LookupListIndex) self.FeatureCount = len(self.FeatureRecord) return self
def test_setslice_cint(self): a = (c_int * 100)(*xrange(1100, 1200)) b = range(1100, 1200) a[32:47] = range(32, 47) self.assertEqual(a[32:47], range(32, 47)) a[32:47] = range(132, 147) self.assertEqual(a[32:47:], range(132, 147)) a[46:31:-1] = range(232, 247) self.assertEqual(a[32:47:1], range(246, 231, -1)) a[32:47] = range(1132, 1147) self.assertEqual(a[:], b) a[32:47:7] = range(3) b[32:47:7] = range(3) self.assertEqual(a[:], b) a[33::-3] = range(12) b[33::-3] = range(12) self.assertEqual(a[:], b) from operator import setslice, setitem # TypeError: int expected instead of str instance self.assertRaises(TypeError, setslice, a, 0, 5, "abcde") self.assertRaises(TypeError, setitem, a, slice(0, 5), "abcde") # TypeError: int expected instead of str instance self.assertRaises(TypeError, setslice, a, 0, 5, ["a", "b", "c", "d", "e"]) self.assertRaises(TypeError, setitem, a, slice(0, 5), ["a", "b", "c", "d", "e"]) # TypeError: int expected instead of float instance self.assertRaises(TypeError, setslice, a, 0, 5, [1, 2, 3, 4, 3.14]) self.assertRaises(TypeError, setitem, a, slice(0, 5), [1, 2, 3, 4, 3.14]) # ValueError: Can only assign sequence of same size self.assertRaises(ValueError, setslice, a, 0, 5, range(32)) self.assertRaises(ValueError, setitem, a, slice(0, 5), range(32))
def test_char_ptr(self): s = "abcdefghijklmnopqrstuvwxyz" dll = CDLL(_ctypes_test.__file__) dll.my_strdup.restype = POINTER(c_char) dll.my_free.restype = None res = dll.my_strdup(s) self.assertEqual(res[:len(s)], s) self.assertEqual(res[:3], s[:3]) self.assertEqual(res[:len(s):], s) self.assertEqual(res[len(s)-1:-1:-1], s[::-1]) self.assertEqual(res[len(s)-1:5:-7], s[:5:-7]) self.assertEqual(res[0:-1:-1], s[0::-1]) import operator self.assertRaises(ValueError, operator.getitem, res, slice(None, None, None)) self.assertRaises(ValueError, operator.getitem, res, slice(0, None, None)) self.assertRaises(ValueError, operator.getitem, res, slice(None, 5, -1)) self.assertRaises(ValueError, operator.getitem, res, slice(-5, None, None)) self.assertRaises(TypeError, operator.setslice, res, 0, 5, u"abcde") self.assertRaises(TypeError, operator.setitem, res, slice(0, 5), u"abcde") dll.my_free(res) dll.my_strdup.restype = POINTER(c_byte) res = dll.my_strdup(s) self.assertEqual(res[:len(s)], range(ord("a"), ord("z")+1)) self.assertEqual(res[:len(s):], range(ord("a"), ord("z")+1)) dll.my_free(res)
def test_wchar_ptr(self): s = u"abcdefghijklmnopqrstuvwxyz\0" dll = CDLL(_ctypes_test.__file__) dll.my_wcsdup.restype = POINTER(c_wchar) dll.my_wcsdup.argtypes = POINTER(c_wchar), dll.my_free.restype = None res = dll.my_wcsdup(s) self.assertEqual(res[:len(s)], s) self.assertEqual(res[:len(s):], s) self.assertEqual(res[len(s)-1:-1:-1], s[::-1]) self.assertEqual(res[len(s)-1:5:-7], s[:5:-7]) import operator self.assertRaises(TypeError, operator.setslice, res, 0, 5, u"abcde") self.assertRaises(TypeError, operator.setitem, res, slice(0, 5), u"abcde") dll.my_free(res) if sizeof(c_wchar) == sizeof(c_short): dll.my_wcsdup.restype = POINTER(c_short) elif sizeof(c_wchar) == sizeof(c_int): dll.my_wcsdup.restype = POINTER(c_int) elif sizeof(c_wchar) == sizeof(c_long): dll.my_wcsdup.restype = POINTER(c_long) else: self.skipTest('Pointers to c_wchar are not supported') res = dll.my_wcsdup(s) tmpl = range(ord("a"), ord("z")+1) self.assertEqual(res[:len(s)-1], tmpl) self.assertEqual(res[:len(s)-1:], tmpl) self.assertEqual(res[len(s)-2:-1:-1], tmpl[::-1]) self.assertEqual(res[len(s)-2:5:-7], tmpl[:5:-7]) dll.my_free(res) ################################################################
def test_cdata_errors(self): CDATA = self.etree.CDATA Element = self.etree.Element root = Element("root") cdata = CDATA('test') self.assertRaises(TypeError, root.set, 'attr', cdata) self.assertRaises(TypeError, operator.setitem, root.attrib, 'attr', cdata)
def test_setslice_step_overrun(self): Element = self.etree.Element SubElement = self.etree.SubElement try: slice except NameError: print("slice() not found") return a = Element('a') b = SubElement(a, 'b') c = SubElement(a, 'c') d = SubElement(a, 'd') e = SubElement(a, 'e') x = Element('x') y = Element('y') z = Element('z') self.assertRaises( ValueError, operator.setitem, a, slice(1,None,2), [x, y, z]) self.assertEqual( [b, c, d, e], list(a))
def test_setitem_indexerror(self): Element = self.etree.Element SubElement = self.etree.SubElement a = Element('a') b = SubElement(a, 'b') self.assertRaises(IndexError, operator.setitem, a, 1, Element('c'))
def test_setitem(self): a = list(range(3)) self.assertRaises(TypeError, operator.setitem, a) self.assertRaises(TypeError, operator.setitem, a, None, None) self.assertTrue(operator.setitem(a, 0, 2) is None) self.assertTrue(a == [2, 1, 2]) self.assertRaises(IndexError, operator.setitem, a, 4, 2)
def test_buffer(self): a = array.array(self.typecode, self.example) m = memoryview(a) expected = m.tobytes() self.assertEqual(a.tobytes(), expected) self.assertEqual(a.tobytes()[0], expected[0]) # Resizing is forbidden when there are buffer exports. # For issue 4509, we also check after each error that # the array was not modified. if support.check_impl_detail(pypy=True): # PyPy export buffers differently, and allows reallocation # of the underlying object. return self.assertRaises(BufferError, a.append, a[0]) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, a.extend, a[0:1]) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, a.remove, a[0]) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, a.pop, 0) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, a.fromlist, a.tolist()) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, a.frombytes, a.tobytes()) self.assertEqual(m.tobytes(), expected) if self.typecode == 'u': self.assertRaises(BufferError, a.fromunicode, a.tounicode()) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, operator.imul, a, 2) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, operator.imul, a, 0) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, operator.setitem, a, slice(0, 0), a) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, operator.delitem, a, 0) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, operator.delitem, a, slice(0, 1)) self.assertEqual(m.tobytes(), expected)
def test_setslice_cint(self): a = (c_int * 100)(*range(1100, 1200)) b = list(range(1100, 1200)) a[32:47] = list(range(32, 47)) self.assertEqual(a[32:47], list(range(32, 47))) a[32:47] = range(132, 147) self.assertEqual(a[32:47:], list(range(132, 147))) a[46:31:-1] = range(232, 247) self.assertEqual(a[32:47:1], list(range(246, 231, -1))) a[32:47] = range(1132, 1147) self.assertEqual(a[:], b) a[32:47:7] = range(3) b[32:47:7] = range(3) self.assertEqual(a[:], b) a[33::-3] = range(12) b[33::-3] = range(12) self.assertEqual(a[:], b) from operator import setitem # TypeError: int expected instead of str instance self.assertRaises(TypeError, setitem, a, slice(0, 5), "abcde") # TypeError: int expected instead of str instance self.assertRaises(TypeError, setitem, a, slice(0, 5), ["a", "b", "c", "d", "e"]) # TypeError: int expected instead of float instance self.assertRaises(TypeError, setitem, a, slice(0, 5), [1, 2, 3, 4, 3.14]) # ValueError: Can only assign sequence of same size self.assertRaises(ValueError, setitem, a, slice(0, 5), range(32))
def test_wchar_ptr(self): s = "abcdefghijklmnopqrstuvwxyz\0" dll = CDLL(_ctypes_test.__file__) dll.my_wcsdup.restype = POINTER(c_wchar) dll.my_wcsdup.argtypes = POINTER(c_wchar), dll.my_free.restype = None res = dll.my_wcsdup(s) self.assertEqual(res[:len(s)], s) self.assertEqual(res[:len(s):], s) self.assertEqual(res[len(s)-1:-1:-1], s[::-1]) self.assertEqual(res[len(s)-1:5:-7], s[:5:-7]) import operator self.assertRaises(TypeError, operator.setitem, res, slice(0, 5), "abcde") dll.my_free(res) if sizeof(c_wchar) == sizeof(c_short): dll.my_wcsdup.restype = POINTER(c_short) elif sizeof(c_wchar) == sizeof(c_int): dll.my_wcsdup.restype = POINTER(c_int) elif sizeof(c_wchar) == sizeof(c_long): dll.my_wcsdup.restype = POINTER(c_long) else: return res = dll.my_wcsdup(s) tmpl = list(range(ord("a"), ord("z")+1)) self.assertEqual(res[:len(s)-1], tmpl) self.assertEqual(res[:len(s)-1:], tmpl) self.assertEqual(res[len(s)-2:-1:-1], tmpl[::-1]) self.assertEqual(res[len(s)-2:5:-7], tmpl[:5:-7]) dll.my_free(res) ################################################################
def testTopLevelExtensionsForRepeatedScalar(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.repeated_string_extension self.assertEqual(0, len(extendee_proto.Extensions[extension])) extendee_proto.Extensions[extension].append('foo') self.assertEqual(['foo'], extendee_proto.Extensions[extension]) string_list = extendee_proto.Extensions[extension] extendee_proto.ClearExtension(extension) self.assertEqual(0, len(extendee_proto.Extensions[extension])) self.assertTrue(string_list is not extendee_proto.Extensions[extension]) # Shouldn't be allowed to do Extensions[extension] = 'a' self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions, extension, 'a')
def test_setitem(self): a = range(3) self.assertRaises(TypeError, operator.setitem, a) self.assertRaises(TypeError, operator.setitem, a, None, None) self.assertTrue(operator.setitem(a, 0, 2) is None) self.assertTrue(a == [2, 1, 2]) self.assertRaises(IndexError, operator.setitem, a, 4, 2)
def _change(self, key, oldv, newv): """Analyze changed values and trigger changed events on dependencies.""" if oldv is missing: # add vdep = EventDependency(tracker=self._tracker) self._key_dependencies[key] = vdep if self._is_immutable(newv): self._all_immutables.follow(vdep) else: self._follow_reactive(newv, key=key) change = (operator.setitem, (self, key, newv)) vdep.changed(change) self._structure.changed(change) elif newv is missing: # delete vdep = self._key_dependencies.pop(key) change = (operator.delitem, (self, key)) vdep.changed(change) self._structure.changed(change) if self._is_immutable(oldv): self._all_immutables.unfollow(vdep) else: self._follow_reactive(oldv, stop=True) else: # change is_immu = self._is_immutable(newv) if oldv is newv or (is_immu and self._equal(oldv, newv)): return was_reactive = isinstance(oldv, ReactiveContainerBase) is_reactive = isinstance(newv, ReactiveContainerBase) dep = self._key_dependencies[key] if was_reactive: self._follow_reactive(oldv, stop=True) if is_reactive: self._follow_reactive(newv) dep.changed((operator.setitem, (self, key, newv)))
def _follow_transform(self, followed, key, *changes): change = (operator.setitem, (self, key, followed)) return (change,) + changes
def rotate_row(grid, y, n): rotate(lambda i: grid[y][i], lambda i, v: operator.setitem(grid[y], i, v), n, len(grid[y]))