Search code examples
pythonfunctiondefault-parameters

Default argument alternative to None?


I am writing a function a little 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 the function to return 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])

What I have tried to fix this is:

_DEFAULT = object()

def parse(string, default=_DEFAULT):
    ...
        if default is not _DEFAULT:
            ...

But this seems like I'm overthinking it, and it seems like there's an easier way to do it.

The any and all functions do this (Allowing None as a default), but I don't know how.


Solution

  • Unless you're frequently needing to ignore the ParseError, I would just let parse throw all of the time, and only catch it in the places I need to:

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

    Though if you must have a default value, then the _DEFAULT solution is OK.