Pythonic isinstance on floats and ints
Say you have a function:
def divide(a, b):
return a / b
This will obviously give a different result if a and b are float, int, or
a combination. If you only care about the situation when a and b are
floats, what is the best way to deal with this?
i)
def divide(a, b):
if not isinstance(a, float):
raise TypeError('a must be a float')
if not isinstance(b, float):
raise TypeError('b must be a float')
return a / b
ii)
def divide(a, b):
return float(a) / float(b)
iii) something else?
My preference is for ii), but a colleague argues that if you are using a
and b elsewhere, then i) is more likely to prevent bugs.
This is obviously a somewhat trivial example, but my colleague has much
more experience with C and I am struggling to explain why using isinstance
doesn't really fit with duck-typing and that having it permeate through in
our python code is not great.
No comments:
Post a Comment