Getting the keyword arguments actually passed to a Python method

前端 未结 8 726
挽巷
挽巷 2020-12-24 03:45

I\'m dreaming of a Python method with explicit keyword args:

def func(a=None, b=None, c=None):
    for arg, val in magic_arg_dict.items():   # Where do I get         


        
8条回答
  •  攒了一身酷
    2020-12-24 04:11

    This is easiest accomplished with a single instance of a sentry object:

    # Top of module, does not need to be exposed in __all__
    missing = {}
    
    # Function prototype
    def myFunc(a = missing, b = missing, c = missing):
        if a is not missing:
            # User specified argument a
        if b is missing:
            # User did not specify argument b
    

    The nice thing about this approach is that, since we're using the "is" operator, the caller can pass an empty dict as the argument value, and we'll still pick up that they did not mean to pass it. We also avoid nasty decorators this way, and keep our code a little cleaner.

提交回复
热议问题