Getting the keyword arguments actually passed to a Python method

前端 未结 8 727
挽巷
挽巷 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:04

    I was inspired by lost-theory's decorator goodness, and after playing about with it for a bit came up with this:

    def actual_kwargs():
        """
        Decorator that provides the wrapped function with an attribute 'actual_kwargs'
        containing just those keyword arguments actually passed in to the function.
        """
        def decorator(function):
            def inner(*args, **kwargs):
                inner.actual_kwargs = kwargs
                return function(*args, **kwargs)
            return inner
        return decorator
    
    
    if __name__ == "__main__":
    
        @actual_kwargs()
        def func(msg, a=None, b=False, c='', d=0):
            print msg
            for arg, val in sorted(func.actual_kwargs.iteritems()):
                print '  %s: %s' % (arg, val)
    
        func("I'm only passing a", a='a')
        func("Here's b and c", b=True, c='c')
        func("All defaults", a=None, b=False, c='', d=0)
        func("Nothin'")
        try:
            func("Invalid kwarg", e="bogon")
        except TypeError, err:
            print 'Invalid kwarg\n  %s' % err
    

    Which prints this:

    I'm only passing a
      a: a
    Here's b and c
      b: True
      c: c
    All defaults
      a: None
      b: False
      c: 
      d: 0
    Nothin'
    Invalid kwarg
      func() got an unexpected keyword argument 'e'
    

    I'm happy with this. A more flexible approach is to pass the name of the attribute you want to use to the decorator, instead of hard-coding it to 'actual_kwargs', but this is the simplest approach that illustrates the solution.

    Mmm, Python is tasty.

提交回复
热议问题