Default argument alternative to None?
I am writing a function that looks a bit like this:
def parse(string, default=None):
try:
... # Body of function here
except ParseError:
if default is not None:
return default
raise
But then I run into problems if I actually want to return the function None
.
if len(sys.argv) > 4:
if flag.ignore_invalid:
result = parse(sys.argv[4], None) # Still raises error
else:
result = parse(sys.argv[4])
I tried to fix this:
_DEFAULT = object()
def parse(string, default=_DEFAULT):
...
if default is not _DEFAULT:
...
But it looks like I was overdoing it and it seems like there is an easier way to do it.
The functions any
and all
do it (allowing None
by default), but I don't know how to do it.
+3
user4237459
source
to share
2 answers
How about using keyword parameters, then you can check if the user passed anything at all:
def parse(string, **kw):
try:
... # Body of function here
except ParseError:
if 'default' in kw:
return kw['default']
raise
The downside is that you won't get caught if someone misses default
.
+1
source to share