Seriously though, I'm in an never-ending quest to make my code more Pythonic and idiomatic. I was doing some code clean up and found what seems to be an inefficient use of handling types when making a function call -- where I always expect the arguments passed to the function to be of a certain type. Consider this simple example which shows essentially what I was doing:
- Code: Select all
def addNumbers(a, b):
c = float(a) + float(b)
print(c)
a = float(1)
b = float(2)
addNumbers(a, b)
In the function, I have the added safety net of (re)floating the arguments to ensure they're the proper type before I continue, but could also NOT do that and instead do this:
- Code: Select all
def addNumbers(a, b):
if not isinstance(a, float) or not isinstance(b, float):
print('wrong type')
else:
c = a + b
print(c)
a = float(1)
b = float(2)
addNumbers(a, b)
or something similar.
What's the "right" way to handle argument type enforcement? What did they teach you "real" developers in programmer school?
I realize there's a hundred different ways you could do it, but what's "best"?