Python decimal.InvalidOperation() Examples
The following are 30
code examples of decimal.InvalidOperation().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
decimal
, or try the search function
.
Example #1
Source File: test_decimal.py From recruit with Apache License 2.0 | 8 votes |
def test_arith_series_with_array(self, data, all_arithmetic_operators): op_name = all_arithmetic_operators s = pd.Series(data) context = decimal.getcontext() divbyzerotrap = context.traps[decimal.DivisionByZero] invalidoptrap = context.traps[decimal.InvalidOperation] context.traps[decimal.DivisionByZero] = 0 context.traps[decimal.InvalidOperation] = 0 # Decimal supports ops with int, but not float other = pd.Series([int(d * 100) for d in data]) self.check_opname(s, op_name, other) if "mod" not in op_name: self.check_opname(s, op_name, s * 2) self.check_opname(s, op_name, 0) self.check_opname(s, op_name, 5) context.traps[decimal.DivisionByZero] = divbyzerotrap context.traps[decimal.InvalidOperation] = invalidoptrap
Example #2
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #3
Source File: queries.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def _percent_delta(self, a, b): """Calculate a percent delta. Args: a (int or float or Decimal) the current value b (int or float or Decimal) the previous value Returns: (Decimal) (a - b) / b * 100 Returns Decimal(0) if b is zero. """ try: return Decimal((a - b) / b * 100) except (DivisionByZero, ZeroDivisionError, InvalidOperation): return None
Example #4
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #5
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #6
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #7
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #8
Source File: statistics.py From benchexec with Apache License 2.0 | 6 votes |
def add_local_summary_statistics(run_set_result, run_set_stats): """ Fill in the "local" values of ColumnStatistics instances in result of get_stats_of_run_set """ for column, column_stats in zip(run_set_result.columns, run_set_stats): if ( column.is_numeric() and column.title in run_set_result.summary and run_set_result.summary[column.title] != "" ): try: column_stats.local = StatValue( util.to_decimal(run_set_result.summary[column.title]) ) except InvalidOperation: pass
Example #9
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #10
Source File: parsers.py From django-rest-framework-xml with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _type_convert(self, value): """ Converts the value returned by the XMl parse into the equivalent Python type """ if value is None: return value try: return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S") except ValueError: pass try: return int(value) except ValueError: pass try: return decimal.Decimal(value) except decimal.InvalidOperation: pass return value
Example #11
Source File: report_db_accessor_base.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def _convert_value(self, value, column_type): """Convert a single value to the specified column type. Args: value (var): A value of any type column_type (type) A Python type Returns: (var): The variable converted to type or None if conversion fails. """ if column_type == Decimal: try: value = Decimal(value).quantize(Decimal(self.decimal_precision)) except InvalidOperation: value = None else: try: value = column_type(value) except ValueError as err: LOG.warning(err) value = None return value
Example #12
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #13
Source File: classified.py From django-classified with MIT License | 6 votes |
def currency(value, currency=None): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return "" # Using Babel's currency formatting # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency kwargs = { 'currency': currency or CURRENCY, 'locale': to_locale(get_language() or settings.LANGUAGE_CODE) } return format_currency(value, **kwargs)
Example #14
Source File: models.py From InvenTree with MIT License | 6 votes |
def take_stock(self, quantity, user, notes=''): """ Remove items from stock """ # Cannot remove items from a serialized part if self.serialized: return False try: quantity = Decimal(quantity) except InvalidOperation: return False if quantity <= 0 or self.infinite: return False if self.updateQuantity(self.quantity - quantity): self.addTransactionNote('Removed {n} items from stock'.format(n=quantity), user, notes=notes, system=True) return True
Example #15
Source File: data_entry_app.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #16
Source File: currency_filters.py From django-accounting with MIT License | 6 votes |
def currency_formatter(value, currency=None): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return "" # Using Babel's currency formatting # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency currency = currency or settings.ACCOUNTING_DEFAULT_CURRENCY kwargs = { 'currency': currency, 'format': getattr(settings, 'CURRENCY_FORMAT', None), 'locale': to_locale(get_language()), } return format_currency(value, **kwargs)
Example #17
Source File: models.py From InvenTree with MIT License | 6 votes |
def stocktake(self, count, user, notes=''): """ Perform item stocktake. When the quantity of an item is counted, record the date of stocktake """ try: count = Decimal(count) except InvalidOperation: return False if count < 0 or self.infinite: return False self.stocktake_date = datetime.now().date() self.stocktake_user = user if self.updateQuantity(count): self.addTransactionNote('Stocktake - counted {n} items'.format(n=count), user, notes=notes, system=True) return True
Example #18
Source File: utils.py From cryptotrader with MIT License | 6 votes |
def safe_div(x, y, eps=(dec_eps, 1e-8)): try: out = dec_con.divide(x, y) except DivisionByZero: out = dec_con.divide(x, y + eps[0]) except InvalidOperation: out = dec_con.divide(x, y + eps[0]) except TypeError: try: out = x / y except ZeroDivisionError: out = x / (y + eps[1]) except TypeError: out = float(x) / (float(y) + eps[1]) return out
Example #19
Source File: utils.py From cryptotrader with MIT License | 6 votes |
def array_normalize(x, float=True): out = convert_to.decimal(x) try: out /= out.sum() except DivisionByZero: out /= (out.sum() + dec_eps) except InvalidOperation: out /= (out.sum() + dec_eps) out[-1] += dec_con.create_decimal('1.00000000') - out.sum() if float: return np.float64(out) else: return out
Example #20
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #21
Source File: test_decimal.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 6 votes |
def test_arith_series_with_array(self, data, all_arithmetic_operators): op_name = all_arithmetic_operators s = pd.Series(data) context = decimal.getcontext() divbyzerotrap = context.traps[decimal.DivisionByZero] invalidoptrap = context.traps[decimal.InvalidOperation] context.traps[decimal.DivisionByZero] = 0 context.traps[decimal.InvalidOperation] = 0 # Decimal supports ops with int, but not float other = pd.Series([int(d * 100) for d in data]) self.check_opname(s, op_name, other) if "mod" not in op_name: self.check_opname(s, op_name, s * 2) self.check_opname(s, op_name, 0) self.check_opname(s, op_name, 5) context.traps[decimal.DivisionByZero] = divbyzerotrap context.traps[decimal.InvalidOperation] = invalidoptrap
Example #22
Source File: widgets.py From Python-GUI-Programming-with-Tkinter with MIT License | 6 votes |
def _focusout_validate(self, **kwargs): valid = True value = self.get() min_val = self.cget('from') max_val = self.cget('to') try: value = Decimal(value) except InvalidOperation: self.error.set('Invalid number string: {}'.format(value)) return False if value < min_val: self.error.set('Value is too low (min {})'.format(min_val)) valid = False if value > max_val: self.error.set('Value is too high (max {})'.format(max_val)) return valid ################## # Module Classes # ##################
Example #23
Source File: python.py From SwiftKitten with MIT License | 6 votes |
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')
Example #24
Source File: validators.py From teleport with Apache License 2.0 | 5 votes |
def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if check_type(input_value, INTEGER_TYPES): return True if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values from decimal import Decimal, InvalidOperation for element in input_value: try: #try to convert any type to int, an invalid conversion raise TypeError or ValueError, doublecheck with Decimal type, if both are valid and equal then then int() value is used value = to_unicode(element) if isinstance(element, bytes) else element decimal_value = Decimal(value) int_value = int(value) if decimal_value == int_value: valid_values.append(int_value) else: return False except (ValueError, TypeError, InvalidOperation): return False if sequence: return valid_values else: return valid_values[0]
Example #25
Source File: utils.py From cryptotrader with MIT License | 5 votes |
def decimal(data): try: return dec_con.create_decimal(data).quantize(convert_to._quantizer) except TypeError: if isinstance(data, np.ndarray): return convert_to._quantize_array(data.astype(str)) else: return Decimal.from_float(np.float64(data)).quantize(convert_to._quantizer) except InvalidOperation: if abs(data) > Decimal('1e20'): raise InvalidOperation("Numeric overflow in convert_to.decimal") elif data == np.nan or math.nan: raise InvalidOperation("NaN encountered in convert_to.decimal") except Exception as e: print(data) print(e) raise e # ZMQ sockets helpers
Example #26
Source File: fields.py From RSSNewsGAE with Apache License 2.0 | 5 votes |
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')
Example #27
Source File: test_functions.py From ibis with Apache License 2.0 | 5 votes |
def operate(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except decimal.InvalidOperation: return decimal.Decimal('NaN') return wrapper
Example #28
Source File: decimal.py From ibis with Apache License 2.0 | 5 votes |
def execute_decimal_unary(op, data, **kwargs): operation_name = type(op).__name__.lower() math_function = getattr(math, operation_name, None) function = getattr( decimal.Decimal, operation_name, lambda x: decimal.Decimal(math_function(x)), ) try: return function(data) except decimal.InvalidOperation: return decimal.Decimal('NaN')
Example #29
Source File: test_utils.py From cryptotrader with MIT License | 5 votes |
def test_convert_to(data): if abs(data) < Decimal('1e18'): number = convert_to.decimal(data) assert number - Decimal.from_float(data).quantize(Decimal('0e-9')) < Decimal("1e-8") elif abs(data) < Decimal('1e33'): with pytest.raises(InvalidOperation): convert_to.decimal(data) else: with pytest.raises(Overflow): convert_to.decimal(data)
Example #30
Source File: validators.py From teleport with Apache License 2.0 | 5 votes |
def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if check_type(input_value, INTEGER_TYPES): return True if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values from decimal import Decimal, InvalidOperation for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError or ValueError, doublecheck with Decimal type, if both are valid and equal then then int() value is used value = to_unicode(element) if isinstance(element, bytes) else element decimal_value = Decimal(value) int_value = int(value) if decimal_value == int_value: valid_values.append(int_value) else: return False except (ValueError, TypeError, InvalidOperation): return False if sequence: return valid_values else: return valid_values[0]