How to check whether optional function parameter is set

前端 未结 10 1357
傲寒
傲寒 2020-12-02 15:06

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 ca

10条回答
  •  北海茫月
    2020-12-02 15:42

    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.

提交回复
热议问题