S
Steven D'Aprano
The eternal conflict between "Look Before You Leap" and "Easier to Ask for
Forgiveness than Permission" (LBYL vs EAFP) continues...
I want to check that a value is a number. Let's say I don't care what sort
of number -- float, int, complex, Fraction, Decimal, something else -- just
that it is a number. Should I:
Look Before I Leap:
from numbers import Number
if isinstance(x, Number):
...
else:
raise TypeError
or Ask Forgiveness:
x + 0
...
where in both cases the ellipsis ... is the code I actually care about.
The second version is more compact and easier to write, but is it easier to
read?
Does your answer change if I then go on to check the range of the number,
e.g. to test that x is positive?
A third option is not to check x at all, and hope that it will blow up at
some arbitrary place in the middle of my code rather than silently do the
wrong thing. I don't like this idea because, even if it fails, it is better
to fail earlier than later.
Comments, thoughts and opinions please.
Forgiveness than Permission" (LBYL vs EAFP) continues...
I want to check that a value is a number. Let's say I don't care what sort
of number -- float, int, complex, Fraction, Decimal, something else -- just
that it is a number. Should I:
Look Before I Leap:
from numbers import Number
if isinstance(x, Number):
...
else:
raise TypeError
or Ask Forgiveness:
x + 0
...
where in both cases the ellipsis ... is the code I actually care about.
The second version is more compact and easier to write, but is it easier to
read?
Does your answer change if I then go on to check the range of the number,
e.g. to test that x is positive?
A third option is not to check x at all, and hope that it will blow up at
some arbitrary place in the middle of my code rather than silently do the
wrong thing. I don't like this idea because, even if it fails, it is better
to fail earlier than later.
Comments, thoughts and opinions please.