Getting the keyword arguments actually passed to a Python method

前端 未结 8 740
挽巷
挽巷 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 03:56

    How about using a decorator to validate the incoming kwargs?

    def validate_kwargs(*keys):
        def entangle(f):
            def inner(*args, **kwargs):
                for key in kwargs:
                    if not key in keys:
                        raise ValueError("Received bad kwarg: '%s', expected: %s" % (key, keys))
                return f(*args, **kwargs)
            return inner
        return entangle
    
    ###
    
    @validate_kwargs('a', 'b', 'c')
    def func(**kwargs):
       for arg,val in kwargs.items():
           print arg, "->", val
    
    func(b=2)
    print '----'
    func(a=3, c=5)
    print '----'
    func(d='not gonna work')
    

    Gives this output:

    b -> 2
    ----
    a -> 3
    c -> 5
    ----
    Traceback (most recent call last):
      File "kwargs.py", line 20, in 
        func(d='not gonna work')
      File "kwargs.py", line 6, in inner
        raise ValueError("Received bad kwarg: '%s', expected: %s" % (key, keys))
    ValueError: Received bad kwarg: 'd', expected: ('a', 'b', 'c')
    

提交回复
热议问题