How to check whether optional function parameter is set

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.

Leave a Comment