LBYL vs EAFP

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 5 13:04:23 CET 2013

```Pete Forman wrote:

> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
>>> I want to check that a value is a number. [...]
>> I'm leaning towards an isinstance check
[...]
> BTW what if the value is Not-a-Number? ;-)

Nothing different, and hopefully exactly what the caller expects. As far as
Python is concerned, NANs are Numbers.

py> NAN = float('nan')
py> from numbers import Number
py> isinstance(NAN, Number)
True

If it's a float NAN, Python doesn't give you much control over what happens
next, but generally any arithmetic operation on a NAN will return a NAN
rather than raise.

If it's a Decimal NAN, the same applies:

py> NAN = decimal.Decimal('nan')
py> NAN + 0
Decimal('NaN')

If it's a Decimal SNAN (signalling NAN), then arithmetic operations signal
InvalidOperation, which by default will raise an exception:

py> SNAN = decimal.Decimal('snan')
py> SNAN + 0
Traceback (most recent call last):
...
decimal.InvalidOperation: sNaN

--
Steven

```