我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用operator.contains()。
def __init__(self, id, type, kinds, compRef, mode='readwrite', action='external', parent=None, defValue=None): """ compRef - (domainless.componentBase) - pointer to the component that owns this property type - (string): type of property (SCA Type or 'struct' or 'structSequence') id - (string): the property ID mode - (string): mode for the property, must be in MODES parent - (Property): the property that contains this instance (e.g., struct that holds a simple) """ self.id = id self.type = type self.compRef = compRef if mode not in self.MODES: print str(mode) + ' is not a valid mode, defaulting to "readwrite"' self.mode = 'readwrite' else: self.mode = mode self.action = action self._parent = parent self.defValue = defValue if kinds: self.kinds = kinds else: # Default to "configure" if no kinds given self.kinds = ('configure',"property")
def upload(handle,filename): f = open(filename,"rb") (base,ext) = os.path.splitext(filename) picext = ".bmp .jpg .jpeg .dib .tif .tiff .gif .png" if(operator.contains(picext,ext)): try: handle.storbinary("STOR " + filename,f,1) except Exception: print "Successful upload." else: print "Successful upload." f.close() return try: handle.storbinary("STOR " + filename,f) except Exception: print "Successful upload." else: print "Successful upload." f.close() return
def __figure_out_task_attribute_and_operator(criteria): swap_operands = False if '__' in criteria: attribute, op = criteria.split('__') op = get_operator_function(op) else: attribute, op = criteria, operator.eq if not hasattr(Task, attribute): if hasattr(Task, attribute + 's'): op = operator.contains attribute += 's' else: raise RuntimeError("Task doesn't have such attribute.") elif op is operator.contains: swap_operands = True return attribute, op, swap_operands
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) with test_support.check_py3k_warnings(): self.assertIs(operator.isCallable(0), False) self.assertIs(operator.isCallable(len), True) self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.isSequenceType(0), False) self.assertIs(operator.isSequenceType([]), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.isMappingType(1), False) self.assertIs(operator.isMappingType({}), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
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 chained_put(chained, id, value, put=None, overwrite=False, contains=op.contains, **kargs): stores_with_write = [s for s in chained.stores if s._write] if len(stores_with_write) == 0: raise PermissionError('put', chained, 'write') record = None putin = [] for store in stores_with_write: if overwrite or not contains(store, id): if put: record = put(store, id, value, **kargs) else: record = store.put(id, value, **kargs) putin.append(store) if (len(putin) == 0 and len(stores_with_write) > 0): raise KeyExistsError(id, chained) return record
def chained_delete(chained, id, delete=None, contains=op.contains): stores_with_delete = [s for s in chained.stores if s._delete] if len(stores_with_delete) == 0: raise PermissionError('delete', chained, 'delete') foundin = [] for store in stores_with_delete: if contains(store, id): foundin.append(store) if delete: delete(store, id) else: store.delete(id) if len(foundin) == 0: raise KeyError(id, chained) else: return foundin
def wait_for_page_contents(url, contents, timeout=120, validate=None): if validate is None: validate = operator.contains start_time = time.time() while True: try: stream = urlopen(url) except (HTTPError, URLError): pass else: page = stream.read() if validate(page, contents): return page if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for contents of ' + url) time.sleep(SLEEP_AMOUNT)
def __init__(self, id, valueType, enum, compRef, kinds,defValue=None, parent=None, mode='readwrite', action='external', structRef=None, structSeqRef=None, structSeqIdx=None): """ Create a new simple property. Arguments: id - The property ID valueType - Type of the property, must be in VALUE_TYPES compRef - Reference to the PropertySet that owns this property defValue - Default Python value for this property (default: None) parent - Parent property that contains this property (default: None) mode - Mode for the property, must be in MODES (default: 'readwrite') action - Allocation action type (default: 'external') Deprecated arguments: structRef, structSeqRef, structSeqIdx """ if valueType not in SCA_TYPES: raise(Exception('"' + str(valueType) + '"' + ' is not a valid valueType, choose from\n ' + str(SCA_TYPES))) # Initialize the parent Property.__init__(self, id, type=valueType, kinds=kinds,compRef=compRef, mode=mode, action=action, parent=parent, defValue=defValue) self.valueType = valueType self.typecode = getTypeCode(self.valueType) if enum != None: self._enums = self._parseEnumerations(enum) else: self._enums = None
def mk_operator(which): ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv, '^':operator.pow, '&&': operator.and_, '||': operator.or_, '!':operator.not_, 'and': operator.and_, 'or': operator.or_, 'not':operator.not_, 'in': lambda x, y: operator.contains(y, x), '=':operator.eq, '<': operator.lt, '<=':operator.le, '>=':operator.ge, '>':operator.gt } return ops[which] # Token makers
def test_contains(self): self.assertRaises(TypeError, operator.contains) self.assertRaises(TypeError, operator.contains, None, None) self.assertTrue(operator.contains(range(4), 2)) self.assertFalse(operator.contains(range(4), 5))
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def get_operator_function(name): if name == 'in': return operator.contains if name not in __operators: __operators[name] = dict(inspect.getmembers(operator))[name] return __operators[name]
def test_contains(self): self.assertRaises(TypeError, operator.contains) self.assertRaises(TypeError, operator.contains, None, None) self.assertTrue(operator.contains(range(4), 2)) self.assertFalse(operator.contains(range(4), 5)) with test_support.check_py3k_warnings(): self.assertTrue(operator.sequenceIncludes(range(4), 2)) self.assertFalse(operator.sequenceIncludes(range(4), 5))
def __contains__(self, other): return self.__cmp(operator.contains, other)
def _in(a, b): return operator.contains(b, a)
def like(a, b): return operator.contains(a.lower(), b.lower())
def __init__(self, **kwargs): super(QASqlExpression, self).__init__(**kwargs) self.operations = {'AND': 'AND', 'OR': 'OR', 'LIKE': like, 'GLOB': operator.contains, "IN": _in, '=': operator.eq, '!=': operator.ne, '<': operator.lt, '<=': operator.le, '>': operator.gt, '>=': operator.ge}
def _op_compare(self, args, op): """Returns True if the specified operator can successfully compare the first item in the args with all the rest. Will return False if only one item is in the list. """ if len(args) < 2: return False if op is operator.contains: bad = args[0] not in args[1:] else: bad = [arg for arg in args[1:] if not op(args[0], arg)] return not bool(bad)
def _in(self, args): """First term is in set of remaining terms.""" return self._op_compare(args, operator.contains)
def in_(x, y): return operator.contains(y, x)
def not_in(x, y): return not operator.contains(y, x)
def chained_contains(chained, id, contains=op.contains): stores_with_read = [s for s in chained.stores if s._read] if len(stores_with_read) == 0: raise PermissionError('contains', chained, 'read') for store in stores_with_read: if store._read and contains(store, id): return True return False