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


source to share


2 answers


If you don't need to ignore often ParseError

, I would just like to parse

throw all the time and only catch it where I need it:

try:
    parse(sys.argv[4])
except ParseError:
    if not flag.ignore_invalid:
        raise

      



Although, if you must have the default, then the solution _DEFAULT

is fine.

+1


source


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







All Articles