user4237459
user4237459

Reputation:

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.

Upvotes: 4

Views: 3912

Answers (2)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26609

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.

Upvotes: 1

thebjorn
thebjorn

Reputation: 27360

How about using keyword parameters, then you can check whether 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 catch if anyone misspells default.

Upvotes: 1

Related Questions