我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用decimal.InvalidOperation()。
def get_integer_digit(value): from typepy import TypeConversionError from typepy.type import RealNumber float_type = RealNumber(value) try: abs_value = abs(float_type.convert()) except TypeConversionError: raise ValueError( "the value must be a number: value='{}' type='{}'".format( value, type(value))) if abs_value.is_zero(): return 1 try: return len(str(abs_value.quantize( Decimal("1."), rounding=decimal.ROUND_DOWN))) except decimal.InvalidOperation as e: raise ValueError(e)
def parse_value(lexer, symbol=None, pos=0): try: if symbol is None: pos, symbol = next(lexer) if symbol == 'null': yield ('null', None) elif symbol == 'true': yield ('boolean', True) elif symbol == 'false': yield ('boolean', False) elif symbol == '[': for event in parse_array(lexer): yield event elif symbol == '{': for event in parse_object(lexer): yield event elif symbol[0] == '"': yield ('string', unescape(symbol[1:-1])) else: try: yield ('number', common.number(symbol)) except decimal.InvalidOperation: raise UnexpectedSymbol(symbol, pos) except StopIteration: raise common.IncompleteJSONError('Incomplete JSON data')
def __call__(self, value): try: if isinstance(value, decimal.Decimal): v = value else: v = decimal.Decimal(str(value).replace(self.dot, '.')) if self.minimum is None: if self.maximum is None or v <= self.maximum: return (v, None) elif self.maximum is None: if v >= self.minimum: return (v, None) elif self.minimum <= v <= self.maximum: return (v, None) except (ValueError, TypeError, decimal.InvalidOperation): pass return (value, self.error_message)
def validate_form(cls, form, cleaned_data): parameter = cleaned_data.get('parameter', '') if not parameter: form.add_error('parameter', _('This field cannot be blank.')) return try: amount = Valute(parameter) except (TypeError, ValueError, InvalidOperation): form.add_error('parameter', _('Invalid value')) return if not amount: form.add_error('parameter', _('Ensure this value is greater than 0')) return return cleaned_data
def validate_form(cls, form, cleaned_data): parameter = cleaned_data.get('parameter', '') if not parameter: form.add_error('parameter', _('This field cannot be blank.')) return try: percentage = Decimal(parameter) except (TypeError, ValueError, InvalidOperation): form.add_error('parameter', _('Invalid value')) return if not percentage: form.add_error('parameter', _('Ensure this value is greater than 0')) return return cleaned_data
def logical_and(self, other, context=None): """Applies an 'and' operation between self and other's digits.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) if not self._islogical() or not other._islogical(): return context._raise_error(InvalidOperation) # fill to context.prec (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) return _dec_from_triple(0, result.lstrip('0') or '0', 0)
def logical_xor(self, other, context=None): """Applies an 'xor' operation between self and other's digits.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) if not self._islogical() or not other._islogical(): return context._raise_error(InvalidOperation) # fill to context.prec (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) return _dec_from_triple(0, result.lstrip('0') or '0', 0)
def scaleb(self, other, context=None): """Returns self operand after adding the second value to its exp.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) ans = self._check_nans(other, context) if ans: return ans if other._exp != 0: return context._raise_error(InvalidOperation) liminf = -2 * (context.Emax + context.prec) limsup = 2 * (context.Emax + context.prec) if not (liminf <= int(other) <= limsup): return context._raise_error(InvalidOperation) if self._isinfinity(): return Decimal(self) d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) d = d._fix(context) return d
def parse_values(self, entries): """Retrieve the values from the data set.""" values = [] for entry in entries: if not entry: continue date, daily, _, _ = entry try: separated = date.split('-', 2) intified = map(int, separated) co2_date = datetime.date(*intified) except (ValueError, TypeError): continue try: co2_ppm = Decimal(daily) except InvalidOperation: continue values.append((co2_date, co2_ppm)) return values
def parse_values(self, entries): """Create new CO2 measurements.""" values = [] for entry in entries: try: co2_date = dt.strptime(entry[0], '%Y-%m-%d') except (ValueError, IndexError): continue try: co2_ppm = Decimal(entry[1]) except (InvalidOperation, IndexError): continue values.append((co2_date, co2_ppm)) return values
def check_and_return(self, data): data = super(DecimalTrafaret, self).check_and_return(data) if self.allow_nan: if data.is_nan(): return decimal.Decimal('NaN') # avoid sNaN, -sNaN and -NaN else: if data.is_nan() or data.is_infinite(): self._failure('Special numeric values are not permitted.', value=data) if self.places is not None and data.is_finite(): try: data = data.quantize(self.places, rounding=self.rounding) except decimal.InvalidOperation: self._failure('Decimal can not be properly quantized.', value=data) return data
def _load_(self, value, context): if isinstance(value, decimal.Decimal): if not self.get_options().allow_nan and not value.is_finite(): raise ValueError() return value elif isinstance(value, text_types): try: with decimal.localcontext() as ctx: ctx.traps[decimal.InvalidOperation] = 1 value = decimal.Decimal(value) if not self.get_options().allow_nan and not value.is_finite(): raise ValueError() return value except decimal.InvalidOperation: raise ValueError() elif isinstance(value, integer_types): return decimal.Decimal(value) elif isinstance(value, float): if not self.get_options().allow_nan: if math.isnan(value) or math.isinf(value): raise ValueError() return decimal.Decimal(value) else: raise ValueError()
def _validate_subscription_number(key, value, description): if not isinstance(value, list): raise jsonschema.exceptions.ValidationError( "{0} value not a list.".format(key) ) if len(value) != 2: raise jsonschema.exceptions.ValidationError( "{0} value {1} does not have two entries.".format(key, value) ) try: lower = Decimal(value[0]) upper = Decimal(value[1]) except InvalidOperation: raise jsonschema.exceptions.ValidationError( "{0} values {1} not numbers.".format(key, value) ) minimum = Decimal(description["minimum"]) maximum = Decimal(description["maximum"]) if not (minimum <= lower <= upper < maximum): # maximum is exclusive raise jsonschema.exceptions.ValidationError( "{0} values {1} not in limits: {2} <= {4} <= {5} < {3}.".format( key, value, minimum, maximum, lower, upper ) )
def _validate_indexes(schema, indexes): if not isinstance(indexes, list): raise jsonschema.exceptions.ValidationError("Indexes must be a list.") maximum = len(schema["indexes"]) for index in indexes: try: number = Decimal(index) except InvalidOperation: raise jsonschema.exceptions.ValidationError( "Index value {0} not a number.".format(index) ) if not (0 <= number < maximum): raise jsonschema.exceptions.ValidationError( "Index value {0} not in limits: {1} <= {0} < {2}.".format( number, 0, maximum ) )
def force_convert(self): if isinstance(self._value, float): return self.float_class(str(self._value)) try: return self.float_class(self._value) except (TypeError, ValueError, decimal.InvalidOperation): raise TypeConversionError( "failed to force_convert to float: type={}".format( type(self._value)))
def validate(self, value): from decimal import Decimal as _Decimal from decimal import InvalidOperation val = super(Decimal, self).validate(value) if val is None: return try: return _Decimal(repr(val)) if isinstance(val, float) else _Decimal(val) except InvalidOperation: raise ValidationError("{0} '{1}' can't be coerced to decimal".format(self.column_name, val))
def parse_decimal(string, locale=LC_NUMERIC): """Parse localized decimal string into a decimal. >>> parse_decimal('1,099.98', locale='en_US') Decimal('1099.98') >>> parse_decimal('1.099,98', locale='de') Decimal('1099.98') When the given string cannot be parsed, an exception is raised: >>> parse_decimal('2,109,998', locale='de') Traceback (most recent call last): ... NumberFormatError: '2,109,998' is not a valid decimal number :param string: the string to parse :param locale: the `Locale` object or locale identifier :raise NumberFormatError: if the string can not be converted to a decimal number """ locale = Locale.parse(locale) try: return Decimal(string.replace(get_group_symbol(locale), '') .replace(get_decimal_symbol(locale), '.')) except InvalidOperation: raise NumberFormatError('%r is not a valid decimal number' % string)
def test0040numeric(self): 'Test numeric' with Transaction().start(DB_NAME, USER, context=CONTEXT): self.assertEqual(self.numeric.import_data(['numeric'], [['1.1']]), 1) self.assertEqual(self.numeric.import_data(['numeric'], [['-1.1']]), 1) self.assertEqual(self.numeric.import_data(['numeric'], [['1']]), 1) self.assertEqual(self.numeric.import_data(['numeric'], [['']]), 1) self.assertEqual(self.numeric.import_data(['numeric'], [['1.1'], ['2.2']]), 2) self.assertRaises(InvalidOperation, self.numeric.import_data, ['numeric'], [['foo']]) self.assertEqual(self.numeric.import_data(['numeric'], [['0']]), 1) self.assertEqual(self.numeric.import_data(['numeric'], [['0.0']]), 1)
def test0041numeric_required(self): 'Test required numeric' with Transaction().start(DB_NAME, USER, context=CONTEXT) as transaction: self.assertEqual(self.numeric_required.import_data(['numeric'], [['1.1']]), 1) self.assertEqual(self.numeric_required.import_data(['numeric'], [['-1.1']]), 1) self.assertEqual(self.numeric_required.import_data(['numeric'], [['1']]), 1) self.assertRaises(UserError, self.numeric_required.import_data, ['numeric'], [['']]) transaction.cursor.rollback() self.assertEqual(self.numeric_required.import_data(['numeric'], [['1.1'], ['2.2']]), 2) self.assertRaises(InvalidOperation, self.numeric_required.import_data, ['numeric'], [['foo']]) self.assertEqual(self.numeric_required.import_data(['numeric'], [['0']]), 1) self.assertEqual(self.numeric_required.import_data(['numeric'], [['0.0']]), 1)
def to_python(self, value): if value is None: return value try: return decimal.Decimal(value) except decimal.InvalidOperation: raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, )
def process_formdata(self, valuelist): if valuelist: try: lat, lon = valuelist[0].split(',') self.data = '%s,%s' % (decimal.Decimal(lat.strip()), decimal.Decimal(lon.strip()),) except (decimal.InvalidOperation, ValueError): raise ValueError('Not a valid coordinate location')
def process_formdata(self, valuelist): if valuelist: try: if self.use_locale: self.data = self._parse_decimal(valuelist[0]) else: self.data = decimal.Decimal(valuelist[0]) except (decimal.InvalidOperation, ValueError): self.data = None raise ValueError(self.gettext('Not a valid decimal value'))
def _parse_x_y(_x, _y): try: x = Decimal(_x) y = Decimal(_y) except (InvalidOperation, TypeError, ValueError): try: x = cast_date(_x)['date'] y = cast_date(_y)['date'] except (ValueError, KeyError, IndexError, TypeError): x, y = _x, _y return x, y
def set_members(self, *args): if not args: # Reset members if nothing was given self._members = [] return new_members = [] for member in args: member = list(member) try: member[1] = decimal.Decimal(str(member[1])) except decimal.InvalidOperation: raise ValueError("Member '{member}' is invalid".format( member=member)) new_members.append(tuple(member)) new_members.sort(key=lambda x: x[1], reverse=True) if self._members == new_members: return self._members = new_members self._nr_members = len(new_members) min_weight = min(i[1] for i in self._members) self._ratios = [] for _, weight in self._members: self._ratios.append(int(weight / min_weight * 100)) self.reset()
def __call__(self, value): try: if isinstance(value, decimal.Decimal): v = value else: v = decimal.Decimal(str(value).replace(self.dot, '.')) if ((self.minimum is None or v >= self.minimum) and (self.maximum is None or v <= self.maximum)): return (v, None) except (ValueError, TypeError, decimal.InvalidOperation): pass return (value, self.error_message)
def _getBpm(self): from decimal import Decimal, ROUND_HALF_UP, InvalidOperation bpm = None if frames.BPM_FID in self.frame_set: bpm_str = self.frame_set[frames.BPM_FID][0].text or u"0" try: # Round floats since the spec says this is an integer. Python3 # changed how 'round' works, hence the using of decimal bpm = int(Decimal(bpm_str).quantize(1, ROUND_HALF_UP)) except (InvalidOperation, ValueError) as ex: log.warning(ex) return bpm
def is_numeric(strin): import decimal # Decimal allows spaces in input, but we don't if strin.strip() != strin: return False try: value = decimal.Decimal(strin) except decimal.InvalidOperation as e: return False return True
def _apply(self, value): allowed_types = (text_type, int, float, DecimalType,) if self.allow_tuples: # Python's Decimal type supports both tuples and lists. # :py:meth:`decimal.Decimal.__init__` allowed_types += (list, tuple,) value = self._filter(value, Type(allowed_types)) if self._has_errors: return value try: d = DecimalType(value) except (InvalidOperation, TypeError, ValueError): return self._invalid_value(value, self.CODE_INVALID, exc_info=True) # Decimal's constructor also accepts values such as 'NaN' or # '+Inf', which aren't valid in this context. # :see: decimal.Decimal._parser if not d.is_finite(): return self._invalid_value( value = value, reason = self.CODE_NON_FINITE, exc_info = True, ) if self.max_precision is not None: d = d.quantize(self.max_precision) return d
def numberise(value, group_symbol, decimal_symbol, currency_symbols): """ Convert a string to a :class:`decimal.Decimal` object, if the string is number-like. A string's considered number-like if it's made up of numbers with or without group and decimal symbols, and optionally suffixed by percent signs, prefixed by a +/- sign, or surrounded by currency symbols. It's pretty lenient, and could easily parse something as a number when it's not, but it's good enough. Args: value: String to attempt to convert to a number group_symbol: symbol used to group digits in numbers (e.g. the ',' in '1,000.00') decimal_symbol: Symbol used to separate integer from fraction in numbers (e.g. the '.' in '1,000.00'). currency_symbols: List of currency symbols. Returns: :class:`decimal.Decimal` Raises: :class:`ValueError`: ``value`` is not numeric """ number = value.strip("%") if len(number) > 0 and number[0] == "-": number = number[1:] sign = Decimal("-1") else: sign = Decimal("1") for symbol in currency_symbols: number = number.strip(symbol) number = number.replace(group_symbol, "") number = number.replace(decimal_symbol, ".") try: return Decimal(number) * sign except InvalidOperation: raise ValueError("{} is not numeric".format(value))
def is_numeric(strin): import decimal strin = str(strin) # Decimal allows spaces in input, but we don't if strin.strip() != strin: return False try: value = decimal.Decimal(strin) except decimal.InvalidOperation as e: return False return True
def process_formdata(self, valuelist): if valuelist: try: self.data = decimal.Decimal(valuelist[0]) except (decimal.InvalidOperation, ValueError): self.data = None raise ValueError(self.gettext('Not a valid decimal value'))
def set_members(self, *args): if not args: # Reset members if nothing was given self._members = [] return new_members = [] for member in args: member = list(member) try: member[1] = decimal.Decimal(str(member[1])) except decimal.InvalidOperation: raise ValueError("Member '{member}' is invalid".format( member=member)) new_members.append(tuple(member)) new_members.sort(key=lambda x: x[1], reverse=True) if self._members == new_members: return self._members = new_members self._nr_members = len(new_members) min_weight = min(i[1] for i in self._members) self._ratios = [] for _, weight in self._members: self._ratios.append(int(weight/min_weight * 100)) self.reset()
def from_xml(self, elem, account): field_elem = elem.find(self.response_tag()) val = None if field_elem is None else field_elem.text or None if val is not None: try: return self.value_cls(val) except (ValueError, InvalidOperation): log.warning("Cannot convert value '%s' on field '%s' to type %s", val, self.name, self.value_cls) return None return self.default