Reputation: 15755
I want to have a function that allows you to set a default return value instead of an error if the result it None. This gives me a function like the following:
def get_name(default=None):
result = get_setting('name')
if result:
return result
elif default:
return default
else:
raise NoNameError
However, this causes a bug when the default value IS None
. How whould I write this so that someone could call get_name(default=None)
and get None back as opposed to an error?
I know I could do a hack such as:
def get_name(default=SomeSingletonObject):
result = get_setting('name')
if result:
return result
elif default is not SomeSingletonObject:
return default
else:
raise NoNameError
But that is just bad form altogether
Upvotes: 0
Views: 446
Reputation: 11039
This is a common pattern used where None
is perfectly acceptable input:
_marker = object()
def foo(val1=_marker):
if val1 is _marker:
do_some_stuff()
Here is a more useful example from the more-itertools library:
def first(iterable, default=_marker):
try:
return next(iter(iterable))
except StopIteration:
if default is _marker:
raise ValueError('first() was called on an empty iterable...')
return default
Upvotes: 3