我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用builtins.bool()。
def _get_conditional_content(self, fname, spans, conditions, contents): out = [] ieval = [] peval = [] multiline = (spans[0][0] != spans[-1][1]) for condition, content, span in zip(conditions, contents, spans): try: cond = bool(self._evaluate(condition, fname, span[0])) except Exception as exc: msg = "exception occured when evaluating '{0}'"\ .format(condition) raise FyppFatalError(msg, fname, span, exc) if cond: if self._linenums and not self._diverted and multiline: out.append(linenumdir(span[1], fname)) outcont, ievalcont, pevalcont = self._render(content) ieval += _shiftinds(ievalcont, len(out)) peval += pevalcont out += outcont break if self._linenums and not self._diverted and multiline: out.append(linenumdir(spans[-1][1], fname)) return out, ieval, peval
def _add_aliases(): for a in typeinfo.keys(): name = english_lower(a) if not isinstance(typeinfo[a], tuple): continue typeobj = typeinfo[a][-1] # insert bit-width version for this class (if relevant) base, bit, char = bitname(typeobj) if base[-3:] == 'int' or char[0] in 'ui': continue if base != '': myname = "%s%d" % (base, bit) if ((name != 'longdouble' and name != 'clongdouble') or myname not in allTypes.keys()): allTypes[myname] = typeobj sctypeDict[myname] = typeobj if base == 'complex': na_name = '%s%d' % (english_capitalize(base), bit//2) elif base == 'bool': na_name = english_capitalize(base) sctypeDict[na_name] = typeobj else: na_name = "%s%d" % (english_capitalize(base), bit) sctypeDict[na_name] = typeobj sctypeNA[na_name] = typeobj sctypeDict[na_name] = typeobj sctypeNA[typeobj] = na_name sctypeNA[typeinfo[a][0]] = na_name if char != '': sctypeDict[char] = typeobj sctypeNA[char] = na_name
def issubclass_(arg1, arg2): """ Determine if a class is a subclass of a second class. `issubclass_` is equivalent to the Python built-in ``issubclass``, except that it returns False instead of raising a TypeError if one of the arguments is not a class. Parameters ---------- arg1 : class Input class. True is returned if `arg1` is a subclass of `arg2`. arg2 : class or tuple of classes. Input class. If a tuple of classes, True is returned if `arg1` is a subclass of any of the tuple elements. Returns ------- out : bool Whether `arg1` is a subclass of `arg2` or not. See Also -------- issubsctype, issubdtype, issctype Examples -------- >>> np.issubclass_(np.int32, np.int) True >>> np.issubclass_(np.int32, np.float) False """ try: return issubclass(arg1, arg2) except TypeError: return False
def issubdtype(arg1, arg2): """ Returns True if first argument is a typecode lower/equal in type hierarchy. Parameters ---------- arg1, arg2 : dtype_like dtype or string representing a typecode. Returns ------- out : bool See Also -------- issubsctype, issubclass_ numpy.core.numerictypes : Overview of numpy type hierarchy. Examples -------- >>> np.issubdtype('S1', str) True >>> np.issubdtype(np.float64, np.float32) False """ if issubclass_(arg2, generic): return issubclass(dtype(arg1).type, arg2) mro = dtype(arg2).type.mro() if len(mro) > 1: val = mro[1] else: val = mro[0] return issubclass(dtype(arg1).type, val) # This dictionary allows look up based on any alias for an array data-type
def str2bool(value): """ Tries to transform a string supposed to represent a boolean to a boolean. Parameters ---------- value : str The string that is transformed to a boolean. Returns ------- boolval : bool The boolean representation of `value`. Raises ------ ValueError If the string is not 'True' or 'False' (case independent) Examples -------- >>> np.lib._iotools.str2bool('TRUE') True >>> np.lib._iotools.str2bool('false') False """ value = value.upper() if value == asbytes('TRUE'): return True elif value == asbytes('FALSE'): return False else: raise ValueError("Invalid boolean")
def render(self, tree, divert=False, fixposition=False): '''Renders a tree. Args: tree (fypp-tree): Tree to render. divert (bool): Whether output will be diverted and sent for further processing, so that no line numbering directives and postprocessing are needed at this stage. (Default: False) fixposition (bool): Whether file name and line position (variables _FILE_ and _LINE_) should be kept at their current values or should be updated continuously. (Default: False). Returns: str: Rendered string. ''' diverted = self._diverted self._diverted = divert fixedposition = self._fixedposition self._fixedposition = fixposition output, eval_inds, eval_pos = self._render(tree) if not self._diverted and eval_inds: self._postprocess_eval_lines(output, eval_inds, eval_pos) self._diverted = diverted self._fixedposition = fixedposition txt = ''.join(output) return txt
def _handle_assert(self, fname, span, expr): result = '' try: cond = bool(self._evaluate(expr, fname, span[0])) except Exception as exc: msg = "exception occured when evaluating assert condition '{0}'"\ .format(expr) raise FyppFatalError(msg, fname, span, exc) if not cond: msg = "Assertion failed ('{0}')".format(expr) raise FyppStopRequest(msg, fname, span) if self._linenums and not self._diverted: result = linenumdir(span[1], fname) return result
def __bool__(self): """The truthy value of a deferred expression. This causes the immediate evaulation of the deferred expression. """ return builtins.bool(self.evaluate())
def __contains__(seq, key): """This method triggers the evaluation of the resulting expression. If you want a really deferred check, you should use `reframe.utility.sanity.contains()`. This happens because Python always converts the result of `__contains__()` to a boolean value by calling `bool()`, which in our case it triggers the evaluation of the expression. """ return key in seq
def assert_true(x, msg=None): """Assert that ``x`` is evaluated to ``True``. :returns: ``True`` on success. :raises reframe.core.exceptions.SanityError: if assertion fails. """ if builtins.bool(x) is not True: error_msg = msg or '{0} is not True' raise SanityError(_format(error_msg, x)) return True
def assert_false(x, msg=None): """Assert that ``x`` is evaluated to ``False``. :returns: ``True`` on success. :raises reframe.core.exceptions.SanityError: if assertion fails. """ if builtins.bool(x) is not False: error_msg = msg or '{0} is not False' raise SanityError(_format(error_msg, x)) return True
def bitname(obj): """Return a bit-width name for a given type object""" name = obj.__name__ base = '' char = '' try: if name[-1] == '_': newname = name[:-1] else: newname = name info = typeinfo[english_upper(newname)] assert(info[-1] == obj) # sanity check bits = info[2] except KeyError: # bit-width name base, bits = _evalname(name) char = base[0] if name == 'bool_': char = 'b' base = 'bool' elif name == 'void': char = 'V' base = 'void' elif name == 'object_': char = 'O' base = 'object' bits = 0 elif name == 'datetime64': char = 'M' elif name == 'timedelta64': char = 'm' if sys.version_info[0] >= 3: if name == 'bytes_': char = 'S' base = 'bytes' elif name == 'str_': char = 'U' base = 'str' else: if name == 'string_': char = 'S' base = 'string' elif name == 'unicode_': char = 'U' base = 'unicode' bytes = bits // 8 if char != '' and bytes != 0: char = "%s%d" % (char, bytes) return base, bits, char
def _set_up_aliases(): type_pairs = [('complex_', 'cdouble'), ('int0', 'intp'), ('uint0', 'uintp'), ('single', 'float'), ('csingle', 'cfloat'), ('singlecomplex', 'cfloat'), ('float_', 'double'), ('intc', 'int'), ('uintc', 'uint'), ('int_', 'long'), ('uint', 'ulong'), ('cfloat', 'cdouble'), ('longfloat', 'longdouble'), ('clongfloat', 'clongdouble'), ('longcomplex', 'clongdouble'), ('bool_', 'bool'), ('unicode_', 'unicode'), ('object_', 'object')] if sys.version_info[0] >= 3: type_pairs.extend([('bytes_', 'string'), ('str_', 'unicode'), ('string_', 'string')]) else: type_pairs.extend([('str_', 'string'), ('string_', 'string'), ('bytes_', 'string')]) for alias, t in type_pairs: allTypes[alias] = allTypes[t] sctypeDict[alias] = sctypeDict[t] # Remove aliases overriding python types and modules to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float', 'complex', 'bool', 'string', 'datetime', 'timedelta'] if sys.version_info[0] >= 3: # Py3K to_remove.append('bytes') to_remove.append('str') to_remove.remove('unicode') to_remove.remove('long') for t in to_remove: try: del allTypes[t] del sctypeDict[t] except KeyError: pass
def issctype(rep): """ Determines whether the given object represents a scalar data-type. Parameters ---------- rep : any If `rep` is an instance of a scalar dtype, True is returned. If not, False is returned. Returns ------- out : bool Boolean result of check whether `rep` is a scalar dtype. See Also -------- issubsctype, issubdtype, obj2sctype, sctype2char Examples -------- >>> np.issctype(np.int32) True >>> np.issctype(list) False >>> np.issctype(1.1) False Strings are also a scalar type: >>> np.issctype(np.dtype('str')) True """ if not isinstance(rep, (type, dtype)): return False try: res = obj2sctype(rep) if res and res != object_: return True return False except: return False
def update(self, func, default=None, testing_value=None, missing_values=asbytes(''), locked=False): """ Set StringConverter attributes directly. Parameters ---------- func : function Conversion function. default : any, optional Value to return by default, that is, when the string to be converted is flagged as missing. If not given, `StringConverter` tries to supply a reasonable default value. testing_value : str, optional A string representing a standard input value of the converter. This string is used to help defining a reasonable default value. missing_values : sequence of str, optional Sequence of strings indicating a missing value. locked : bool, optional Whether the StringConverter should be locked to prevent automatic upgrade or not. Default is False. Notes ----- `update` takes the same parameters as the constructor of `StringConverter`, except that `func` does not accept a `dtype` whereas `dtype_or_func` in the constructor does. """ self.func = func self._locked = locked # Don't reset the default to None if we can avoid it if default is not None: self.default = default self.type = self._dtypeortype(self._getdtype(default)) else: try: tester = func(testing_value or asbytes('1')) except (TypeError, ValueError): tester = None self.type = self._dtypeortype(self._getdtype(tester)) # Add the missing values to the existing set if missing_values is not None: if _is_bytes_like(missing_values): self.missing_values.add(missing_values) elif hasattr(missing_values, '__iter__'): for val in missing_values: self.missing_values.add(val) else: self.missing_values = []