How to check whether optional function parameter is set

Matthias picture Matthias · Feb 7, 2013 · Viewed 85.6k times · Source

Is there an easy way in Python to check whether the value of an optional parameter comes from its default value, or because the user has set it explicitly at the function call?

Answer

ecatmur picture ecatmur · Feb 7, 2013

Not really. The standard way is to use a default value that the user would not be expected to pass, e.g. an object instance:

DEFAULT = object()
def foo(param=DEFAULT):
    if param is DEFAULT:
        ...

Usually you can just use None as the default value, if it doesn't make sense as a value the user would want to pass.

The alternative is to use kwargs:

def foo(**kwargs):
    if 'param' in kwargs:
        param = kwargs['param']
    else:
        ...

However this is overly verbose and makes your function more difficult to use as its documentation will not automatically include the param parameter.