Create a decimal point instance. >>> Decimal('3.14') # string input Decimal('3.14') >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) Decimal('3.14') >>> Decimal(314) # int Decimal('314') >>> D
(cls, value="0", context=None)
| 459 | |
| 460 | # We're immutable, so use __new__ not __init__ |
| 461 | def __new__(cls, value="0", context=None): |
| 462 | """Create a decimal point instance. |
| 463 | |
| 464 | >>> Decimal('3.14') # string input |
| 465 | Decimal('3.14') |
| 466 | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |
| 467 | Decimal('3.14') |
| 468 | >>> Decimal(314) # int |
| 469 | Decimal('314') |
| 470 | >>> Decimal(Decimal(314)) # another decimal instance |
| 471 | Decimal('314') |
| 472 | >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay |
| 473 | Decimal('3.14') |
| 474 | """ |
| 475 | |
| 476 | # Note that the coefficient, self._int, is actually stored as |
| 477 | # a string rather than as a tuple of digits. This speeds up |
| 478 | # the "digits to integer" and "integer to digits" conversions |
| 479 | # that are used in almost every arithmetic operation on |
| 480 | # Decimals. This is an internal detail: the as_tuple function |
| 481 | # and the Decimal constructor still deal with tuples of |
| 482 | # digits. |
| 483 | |
| 484 | self = object.__new__(cls) |
| 485 | |
| 486 | # From a string |
| 487 | # REs insist on real strings, so we can too. |
| 488 | if isinstance(value, str): |
| 489 | m = _parser(value.strip().replace("_", "")) |
| 490 | if m is None: |
| 491 | if context is None: |
| 492 | context = getcontext() |
| 493 | return context._raise_error(ConversionSyntax, |
| 494 | "Invalid literal for Decimal: %r" % value) |
| 495 | |
| 496 | if m.group('sign') == "-": |
| 497 | self._sign = 1 |
| 498 | else: |
| 499 | self._sign = 0 |
| 500 | intpart = m.group('int') |
| 501 | if intpart is not None: |
| 502 | # finite number |
| 503 | fracpart = m.group('frac') or '' |
| 504 | exp = int(m.group('exp') or '0') |
| 505 | self._int = str(int(intpart+fracpart)) |
| 506 | self._exp = exp - len(fracpart) |
| 507 | self._is_special = False |
| 508 | else: |
| 509 | diag = m.group('diag') |
| 510 | if diag is not None: |
| 511 | # NaN |
| 512 | self._int = str(int(diag or '0')).lstrip('0') |
| 513 | if m.group('signal'): |
| 514 | self._exp = 'N' |
| 515 | else: |
| 516 | self._exp = 'n' |
| 517 | else: |
| 518 | # infinity |
no test coverage detected