How to check whether optional function parameter is set

前端 未结 10 1378
傲寒
傲寒 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:49

    The following function decorator, explicit_checker, makes a set of parameter names of all the parameters given explicitly. It adds the result as an extra parameter (explicit_params) to the function. Just do 'a' in explicit_params to check if parameter a is given explicitly.

    def explicit_checker(f):
        varnames = f.func_code.co_varnames
        def wrapper(*a, **kw):
            kw['explicit_params'] = set(list(varnames[:len(a)]) + kw.keys())
            return f(*a, **kw)
        return wrapper
    
    @explicit_checker
    def my_function(a, b=0, c=1, explicit_params=None):
        print a, b, c, explicit_params
        if 'b' in explicit_params:
            pass # Do whatever you want
    
    
    my_function(1)
    my_function(1, 0)
    my_function(1, c=1)
    

提交回复
热议问题