{"record":{"id":"4f0588d6a411556c","repo":"python/cpython","slug":"cannot-convert-r-to-decimal","errorCode":null,"errorMessage":"Cannot convert %r to Decimal","messagePattern":"Cannot convert %r to Decimal","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/_pydecimal.py","lineNumber":611,"sourceCode":"                    raise ValueError(\"The third value in the tuple must \"\n                                     \"be an integer, or one of the \"\n                                     \"strings 'F', 'n', 'N'.\")\n            return self\n\n        if isinstance(value, float):\n            if context is None:\n                context = getcontext()\n            context._raise_error(FloatOperation,\n                \"strict semantics for mixing floats and Decimals are \"\n                \"enabled\")\n            value = Decimal.from_float(value)\n            self._exp  = value._exp\n            self._sign = value._sign\n            self._int  = value._int\n            self._is_special  = value._is_special\n            return self\n\n        raise TypeError(\"Cannot convert %r to Decimal\" % value)\n\n    @classmethod\n    def from_number(cls, number):\n        \"\"\"Converts a real number to a decimal number, exactly.\n\n        >>> Decimal.from_number(314)              # int\n        Decimal('314')\n        >>> Decimal.from_number(0.1)              # float\n        Decimal('0.1000000000000000055511151231257827021181583404541015625')\n        >>> Decimal.from_number(Decimal('3.14'))  # another decimal instance\n        Decimal('3.14')\n        \"\"\"\n        if isinstance(number, (int, Decimal, float)):\n            return cls(number)\n        raise TypeError(\"Cannot convert %r to Decimal\" % number)\n\n    @classmethod\n    def from_float(cls, f):","sourceCodeStart":593,"sourceCodeEnd":629,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pydecimal.py#L593-L629","documentation":"Decimal(value) supports str, int, float (with FloatOperation signal semantics), list/tuple triples, another Decimal, and internal _WorkRep values. Any other type falls through to this TypeError: 'Cannot convert %r to Decimal'. It is the catch-all rejection at the end of Decimal.__new__.","triggerScenarios":"Decimal(None); Decimal(complex(1, 2)); Decimal(Fraction(1, 3)); Decimal(b'1.5'); Decimal([1.5]) (list with wrong contents fails differently, but a non-numeric type hits this branch).","commonSituations":"Loading YAML/JSON values that parsed as None for null fields; passing a numpy scalar or Fraction where the code assumed int/str; wrapping untrusted input in Decimal without type dispatch.","solutions":["Convert to a supported type first: Decimal(str(fraction)) or Decimal(fraction.numerator) / Decimal(fraction.denominator)","Use Decimal.from_number(x) for int/float/Decimal, or str(x) for numeric strings","Branch on type before constructing when input is heterogeneous"],"exampleFix":"// before\nd = Decimal(value)  # value may be None/Fraction/complex -> TypeError\n\n// after\nif isinstance(value, (str, int, float, Decimal, list, tuple)):\n    d = Decimal(value)\nelse:\n    d = Decimal(str(value))  # or raise your own descriptive error","handlingStrategy":"type-guard","validationCode":"SUPPORTED = (str, int, float, Decimal, list, tuple)\n\ndef can_construct_decimal(v) -> bool:\n    return isinstance(v, SUPPORTED)","typeGuard":"from decimal import Decimal\n\ndef is_decimal_constructible(v) -> bool:\n    return isinstance(v, (str, int, float, list, tuple, Decimal))","tryCatchPattern":"try:\n    d = Decimal(value)\nexcept TypeError:\n    d = Decimal(str(value))  # last resort, or raise a domain-specific error","preventionTips":["Type-dispatch heterogeneous input before calling Decimal()","Reject None explicitly at ingestion instead of letting it reach the constructor","For numpy scalars use Decimal(np_scalar.item()) to get native Python types"],"tags":["decimal","constructor","typeerror","type-conversion"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}