我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用operator.delitem()。
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_encodableUnicodeEnvironment(self): """ Test C{os.environ} (inherited by every subprocess on Windows) that contains an ascii-encodable Unicode string. This is different from passing Unicode environment explicitly to spawnProcess (which is not supported on Python 2). """ os.environ[self.goodKey] = self.goodValue self.addCleanup(operator.delitem, os.environ, self.goodKey) p = GetEnvironmentDictionary.run(reactor, [], properEnv) def gotEnvironment(environ): self.assertEqual( environ[self.goodKey.encode('ascii')], self.goodValue.encode('ascii')) return p.getResult().addCallback(gotEnvironment)
def test_basics(self): from operator import delitem for ct, pt in zip(ctype_types, python_types): i = ct(42) p = pointer(i) ## print type(p.contents), ct self.assertIs(type(p.contents), ct) # p.contents is the same as p[0] ## print p.contents ## self.assertEqual(p.contents, 42) ## self.assertEqual(p[0], 42) self.assertRaises(TypeError, delitem, p, 0)
def test_del_attribute_ns(self): Element = self.etree.Element a = Element('a') a.attrib['{http://a/}foo'] = 'Foo' a.attrib['{http://a/}bar'] = 'Bar' self.assertEqual(None, a.get('foo')) self.assertEqual('Foo', a.get('{http://a/}foo')) self.assertEqual('Foo', a.attrib['{http://a/}foo']) self.assertRaises(KeyError, operator.delitem, a.attrib, 'foo') self.assertEqual('Foo', a.attrib['{http://a/}foo']) del a.attrib['{http://a/}foo'] self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')
def test_del_attribute_ns_parsed(self): XML = self.etree.XML a = XML(_bytes('<a xmlns:nsa="http://a/" nsa:foo="FooNS" foo="Foo" />')) self.assertEqual('Foo', a.attrib['foo']) self.assertEqual('FooNS', a.attrib['{http://a/}foo']) del a.attrib['foo'] self.assertEqual('FooNS', a.attrib['{http://a/}foo']) self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') self.assertRaises(KeyError, operator.delitem, a.attrib, 'foo') del a.attrib['{http://a/}foo'] self.assertRaises(KeyError, operator.getitem, a.attrib, '{http://a/}foo') self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') a = XML(_bytes('<a xmlns:nsa="http://a/" foo="Foo" nsa:foo="FooNS" />')) self.assertEqual('Foo', a.attrib['foo']) self.assertEqual('FooNS', a.attrib['{http://a/}foo']) del a.attrib['foo'] self.assertEqual('FooNS', a.attrib['{http://a/}foo']) self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') del a.attrib['{http://a/}foo'] self.assertRaises(KeyError, operator.getitem, a.attrib, '{http://a/}foo') self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')
def test_delitem(self): a = [4, 3, 2, 1] self.assertRaises(TypeError, operator.delitem, a) self.assertRaises(TypeError, operator.delitem, a, None) self.assertTrue(operator.delitem(a, 1) is None) self.assertTrue(a == [4, 2, 1])
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_basics(self): from operator import delitem for ct, pt in zip(ctype_types, python_types): i = ct(42) p = pointer(i) ## print type(p.contents), ct self.assertTrue(type(p.contents) is ct) # p.contents is the same as p[0] ## print p.contents ## self.assertTrue(p.contents == 42) ## self.assertTrue(p[0] == 42) self.assertRaises(TypeError, delitem, p, 0)
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 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. 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_simple(self): # create classes holding simple numeric types, and check # various properties. init = range(15, 25) for fmt in formats: alen = len(init) int_array = ARRAY(fmt, alen) ia = int_array(*init) # length of instance ok? self.assertEqual(len(ia), alen) # slot values ok? values = [ia[i] for i in range(len(init))] self.assertEqual(values, init) # change the items from operator import setitem new_values = range(42, 42+alen) [setitem(ia, n, new_values[n]) for n in range(alen)] values = [ia[i] for i in range(len(init))] self.assertEqual(values, new_values) # are the items initialized to 0? ia = int_array() values = [ia[i] for i in range(len(init))] self.assertEqual(values, [0] * len(init)) # Too many initializers should be caught self.assertRaises(IndexError, int_array, *range(alen*2)) CharArray = ARRAY(c_char, 3) ca = CharArray("a", "b", "c") # Should this work? It doesn't: # CharArray("abc") self.assertRaises(TypeError, CharArray, "abc") self.assertEqual(ca[0], "a") self.assertEqual(ca[1], "b") self.assertEqual(ca[2], "c") self.assertEqual(ca[-3], "a") self.assertEqual(ca[-2], "b") self.assertEqual(ca[-1], "c") self.assertEqual(len(ca), 3) # slicing is now supported, but not extended slicing (3-argument)! from operator import getslice, delitem self.assertRaises(TypeError, getslice, ca, 0, 1, -1) # cannot delete items self.assertRaises(TypeError, delitem, ca, 0)
def test_simple(self): # create classes holding simple numeric types, and check # various properties. init = list(range(15, 25)) for fmt in formats: alen = len(init) int_array = ARRAY(fmt, alen) ia = int_array(*init) # length of instance ok? self.assertEqual(len(ia), alen) # slot values ok? values = [ia[i] for i in range(len(init))] self.assertEqual(values, init) # change the items from operator import setitem new_values = list(range(42, 42+alen)) [setitem(ia, n, new_values[n]) for n in range(alen)] values = [ia[i] for i in range(len(init))] self.assertEqual(values, new_values) # are the items initialized to 0? ia = int_array() values = [ia[i] for i in range(len(init))] self.assertEqual(values, [0] * len(init)) # Too many initializers should be caught self.assertRaises(IndexError, int_array, *range(alen*2)) CharArray = ARRAY(c_char, 3) ca = CharArray(b"a", b"b", b"c") # Should this work? It doesn't: # CharArray("abc") self.assertRaises(TypeError, CharArray, "abc") self.assertEqual(ca[0], b"a") self.assertEqual(ca[1], b"b") self.assertEqual(ca[2], b"c") self.assertEqual(ca[-3], b"a") self.assertEqual(ca[-2], b"b") self.assertEqual(ca[-1], b"c") self.assertEqual(len(ca), 3) # cannot delete items from operator import delitem self.assertRaises(TypeError, delitem, ca, 0)
def test_simple(self): # create classes holding simple numeric types, and check # various properties. init = range(15, 25) for fmt in formats: alen = len(init) int_array = ARRAY(fmt, alen) ia = int_array(*init) # length of instance ok? self.assertEqual(len(ia), alen) # slot values ok? values = [ia[i] for i in range(alen)] self.assertEqual(values, init) # out-of-bounds accesses should be caught with self.assertRaises(IndexError): ia[alen] with self.assertRaises(IndexError): ia[-alen-1] # change the items from operator import setitem new_values = range(42, 42+alen) [setitem(ia, n, new_values[n]) for n in range(alen)] values = [ia[i] for i in range(alen)] self.assertEqual(values, new_values) # are the items initialized to 0? ia = int_array() values = [ia[i] for i in range(alen)] self.assertEqual(values, [0] * alen) # Too many initializers should be caught self.assertRaises(IndexError, int_array, *range(alen*2)) CharArray = ARRAY(c_char, 3) ca = CharArray("a", "b", "c") # Should this work? It doesn't: # CharArray("abc") self.assertRaises(TypeError, CharArray, "abc") self.assertEqual(ca[0], "a") self.assertEqual(ca[1], "b") self.assertEqual(ca[2], "c") self.assertEqual(ca[-3], "a") self.assertEqual(ca[-2], "b") self.assertEqual(ca[-1], "c") self.assertEqual(len(ca), 3) # slicing is now supported, but not extended slicing (3-argument)! from operator import getslice, delitem self.assertRaises(TypeError, getslice, ca, 0, 1, -1) # cannot delete items self.assertRaises(TypeError, delitem, ca, 0)
def standard_env(): _env = Env() _env.update(vars(math)) _env.update({ # maths '+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv, '//': op.floordiv, '%': op.mod, '**': lambda a, b: a ** b, # binaires '^': op.xor, '|': op.or_, '~': lambda a: ~a, '&': op.and_, 'rshift': lambda a, b: a >> b, 'lshift': lambda a, b: a << b, # Conditions '>': op.gt, '<': op.lt, '>=': op.ge, '<=': op.le, '!=': op.ne, '==': op.eq, '&&': lambda a, b: a and b, # listes '@': op.getitem, '@=': lambda lst, v: op.setitem(lst, v[0], v[1]), '@~': op.delitem, 'length': len, '@@': lambda x: x[1:], 'count': lambda x, y: x.count(y), 'cons': lambda x, y: [x] + y if not isinstance(x, list) and isinstance(y, list) else x + [y], 'setitem': op.setitem, # strings 'split': lambda x, y: x.split(y), 'concat': lambda *x: "".join(str(c) for c in x), # autres 'time': time.time, 'round': round, 'abs': abs, 'zip': lambda *x: list(zip(*x)), 'map': lambda *x: list(map(*x)), 'max': max, 'min': min, 'print': lambda *x: print(mtoa(*x), flush=True), 'printc': lambda x: print(x, end='', flush=True), 'input': input, 'include': lambda x: _env.update({x: __import__(x)}), # fichiers 'open-input-file': lambda f: open(f, 'r'), 'open-output-file': lambda f: open(f, 'w'), 'close-file': lambda f: f.close(), 'read-file': lambda f: f.read(), 'write-in-file': lambda f, s: f.write(s), # types 'int': lambda x: int(x), 'float': lambda x: float(x), 'number?': lambda x: isinstance(x, (int, float)), 'bool': lambda x: bool(x), 'bool?': lambda x: isinstance(x, bool), 'str': lambda x: str(x), 'str?': lambda x: isinstance(x, str), 'list': lambda *x: list(x), 'list?': lambda x: isinstance(x, list), 'dict': lambda k, v: dict(zip(k, v)), 'dict?': lambda x: isinstance(x, dict), 'type': lambda x: type(x).__name__, # constantes '$10': '\n', '$13': '\r', '$9': '\t', }) return _env