I would like to return a custom set of messages based on the specific cause of the TypeError
.
def f(x, y):
value = x + y
return "Success! ({})".format(value)
def safe(function, *args):
try:
result = function(*args)
except TypeError:
if "not_enough_args": # What actual condition can go here?
return "Not enough arguments."
elif "too_many_args": # What actual condition can go here?
return "Too many arguments."
else:
return "A TypeError occurred!"
else:
return result
safe(f, 2) # "Not enough arguments."
safe(f, 2, 2) # "Success!"
safe(f, 2, 2, 2) # "Too many arguments."
safe(f, '2', 2) # "A TypeError occurred!"
Use of the actual TypeError
object would be preferable.