我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.getitem()。
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 compile(self, ttFont): vorgs = list(self.VOriginRecords.values()) names = list(self.VOriginRecords.keys()) nameMap = ttFont.getReverseGlyphMap() lenRecords = len(vorgs) try: gids = map(operator.getitem, [nameMap]*lenRecords, names) except KeyError: nameMap = ttFont.getReverseGlyphMap(rebuild=True) gids = map(operator.getitem, [nameMap]*lenRecords, names) vOriginTable = list(zip(gids, vorgs)) self.numVertOriginYMetrics = lenRecords vOriginTable.sort() # must be in ascending GID order dataList = [ struct.pack(">Hh", rec[0], rec[1]) for rec in vOriginTable] header = struct.pack(">HHhH", self.majorVersion, self.minorVersion, self.defaultVertOriginY, self.numVertOriginYMetrics) dataList.insert(0, header) data = bytesjoin(dataList) return data
def test_index_and_slice(self, size): t = (None,) * size self.assertEqual(len(t), size) self.assertEqual(t[-1], None) self.assertEqual(t[5], None) self.assertEqual(t[size - 1], None) self.assertRaises(IndexError, operator.getitem, t, size) self.assertEqual(t[:5], (None,) * 5) self.assertEqual(t[-5:], (None,) * 5) self.assertEqual(t[20:25], (None,) * 5) self.assertEqual(t[-25:-20], (None,) * 5) self.assertEqual(t[size - 5:], (None,) * 5) self.assertEqual(t[size - 5:size], (None,) * 5) self.assertEqual(t[size - 6:size - 2], (None,) * 4) self.assertEqual(t[size:size], ()) self.assertEqual(t[size:size+5], ()) # Like test_concat, split in two.
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 test_recordIndexable(self): """ The user record returned by I{getpwuid}, I{getpwnam}, and I{getpwall} is indexable, with successive indexes starting from 0 corresponding to the values of the C{pw_name}, C{pw_passwd}, C{pw_uid}, C{pw_gid}, C{pw_gecos}, C{pw_dir}, and C{pw_shell} attributes, respectively. """ db = self.database username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo() for entry in [db.getpwuid(uid), db.getpwnam(username), db.getpwall()[0]]: self.assertEqual(entry[0], username) self.assertEqual(entry[1], password) self.assertEqual(entry[2], uid) self.assertEqual(entry[3], gid) self.assertEqual(entry[4], gecos) self.assertEqual(entry[5], dir) self.assertEqual(entry[6], shell) self.assertEqual(len(entry), len(list(entry))) self.assertRaises(IndexError, getitem, entry, 7)
def test_recordIndexable(self): """ The shadow user record returned by I{getpwnam} and I{getspall} is indexable, with successive indexes starting from 0 corresponding to the values of the C{sp_nam}, C{sp_pwd}, C{sp_lstchg}, C{sp_min}, C{sp_max}, C{sp_warn}, C{sp_inact}, C{sp_expire}, and C{sp_flag} attributes, respectively. """ db = self.database (username, password, lastChange, min, max, warn, inact, expire, flag) = self.getExistingUserInfo() for entry in [db.getspnam(username), db.getspall()[0]]: self.assertEqual(entry[0], username) self.assertEqual(entry[1], password) self.assertEqual(entry[2], lastChange) self.assertEqual(entry[3], min) self.assertEqual(entry[4], max) self.assertEqual(entry[5], warn) self.assertEqual(entry[6], inact) self.assertEqual(entry[7], expire) self.assertEqual(entry[8], flag) self.assertEqual(len(entry), len(list(entry))) self.assertRaises(IndexError, getitem, entry, 9)
def emit(self): """ Add the currently parsed input to the result. """ if self._buffer: attrs = [getattr(attributes, name) for name in self._attrs] attrs.extend(filter(None, [self.foreground, self.background])) if not attrs: attrs.append(attributes.normal) attrs.append(self._buffer) attr = _foldr(operator.getitem, attrs.pop(), attrs) if self._result is None: self._result = attr else: self._result[attr] self._buffer = ''
def __getitem__(self, key): if isinstance(key, str) and key in self.columns: meta = self._meta[key] name = 'getitem-%s' % tokenize(self, key) dsk = {(name, i): (operator.getitem, (self._name, i), key) for i in range(self.npartitions)} return Series(merge(self.dask, dsk), name, meta, self.divisions) raise NotImplementedError("Indexing with %r" % key)
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 __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i]
def __getitem__(self, i): if isinstance(i, slice): return self.clone( operator.getitem(self._value, i) ) else: return self._value[i]
def __getitem__(self, idx): if isinstance(idx, slice): return self.__class__( self.__baseTag, *getitem(self.__superTags, idx) ) return self.__superTags[idx]
def dict_get(datadict, keylist): return reduce(getitem, keylist, datadict)
def dict_get(datadict, keylist): ''' This gets the requested key by walking the datadict. ''' return reduce(getitem, keylist, datadict)
def dict_get(datadict, keylist): return reduce(getitem, keylist, datadict) ############# ## LOGGING ## ############# # setup a logger
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 assert_equal_records(a, b): """ Asserts that two records are equal. Pretty crude for now. """ assert_equal(a.dtype, b.dtype) for f in a.dtype.names: (af, bf) = (operator.getitem(a, f), operator.getitem(b, f)) if not (af is masked) and not (bf is masked): assert_equal(operator.getitem(a, f), operator.getitem(b, f)) return
def test_child_index(self): root = self.XML(xml_str) self.assertEqual("0", root.c1.c2[0].text) self.assertEqual("1", root.c1.c2[1].text) self.assertEqual("2", root.c1.c2[2].text) self.assertRaises(IndexError, operator.getitem, root.c1.c2, 3)
def test_child_index_neg(self): root = self.XML(xml_str) self.assertEqual("0", root.c1.c2[0].text) self.assertEqual("0", root.c1.c2[-3].text) self.assertEqual("1", root.c1.c2[-2].text) self.assertEqual("2", root.c1.c2[-1].text) self.assertRaises(IndexError, operator.getitem, root.c1.c2, -4)
def test_simple(self): Element = self.etree.Element root = Element('root') root.append(Element('one')) root.append(Element('two')) root.append(Element('three')) self.assertEqual(3, len(root)) self.assertEqual('one', root[0].tag) self.assertEqual('two', root[1].tag) self.assertEqual('three', root[2].tag) self.assertRaises(IndexError, operator.getitem, root, 3) # test weird dictionary interaction leading to segfault previously
def test_element_indexing_with_text(self): ElementTree = self.etree.ElementTree f = BytesIO('<doc>Test<one>One</one></doc>') doc = ElementTree(file=f) root = doc.getroot() self.assertEqual(1, len(root)) self.assertEqual('one', root[0].tag) self.assertRaises(IndexError, operator.getitem, root, 1)
def test_element_indexing_negative(self): Element = self.etree.Element SubElement = self.etree.SubElement a = Element('a') b = SubElement(a, 'b') c = SubElement(a, 'c') d = SubElement(a, 'd') self.assertEqual(d, a[-1]) self.assertEqual(c, a[-2]) self.assertEqual(b, a[-3]) self.assertRaises(IndexError, operator.getitem, a, -4) a[-1] = e = Element('e') self.assertEqual(e, a[-1]) del a[-1] self.assertEqual(2, len(a))
def test_attrib_dict(self): ElementTree = self.etree.ElementTree f = BytesIO('<doc one="One" two="Two"/>') doc = ElementTree(file=f) root = doc.getroot() attrib = dict(root.attrib) self.assertEqual('One', attrib['one']) self.assertEqual('Two', attrib['two']) self.assertRaises(KeyError, operator.getitem, attrib, 'three')