Suppose you have a function that can return an object or None:
def foobar(arg):
if arg == 'foo':
return None
else:
return 'bar'
Now you call this method and want to do something with the object, for this example I get str, so I can call the function upper(). There are currently two possible cases where the second will fail because None has no methodupper()
foobar('sdfsdgf').upper()
foobar('foo').upper()
of course, now this is easy to fix:
tmp = foobar('foo')
if tmp is not None:
tmp.upper()
try:
foobar('foo').upper()
except ArgumentError:
pass
caller = lambda x: x.upper() if type(x) is str else None
caller(foobar('foo'))
but the exception handling is probably not abstract enough, and it may happen that I catch an exception that can be important (= debugging gets harder), while the first method is good, but it can lead to code increase, and the third option looks pretty good but you have to do this for all possible functions, so method one is probably the best.
, - , ?