Why is not 'decimal.Decimal(1)' an instance of 'numbers.Real'?

后端 未结 1 1372
情话喂你
情话喂你 2020-12-11 02:04

I try to check if a variable is an instance of a number of any type (int, float, Fraction, Decimal, etc.).

I cam

相关标签:
1条回答
  • 2020-12-11 02:28

    So, I found the answer directly in the source code of cpython/numbers.py:

    ## Notes on Decimal
    ## ----------------
    ## Decimal has all of the methods specified by the Real abc, but it should
    ## not be registered as a Real because decimals do not interoperate with
    ## binary floats (i.e.  Decimal('3.14') + 2.71828 is undefined).  But,
    ## abstract reals are expected to interoperate (i.e. R1 + R2 should be
    ## expected to work if R1 and R2 are both Reals).
    

    Indeed, adding Decimal to float would raise a TypeError.

    In my point of view, it violates the principle of least astonishment, but it does not matter much.

    As a workaround, I use:

    import numbers
    import decimal
    
    Real = (numbers.Real, decimal.Decimal)
    
    print(isinstance(decimal.Decimal(1), Real))
    # True
    
    0 讨论(0)
提交回复
热议问题