Getting the keyword arguments actually passed to a Python method

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

    Perhaps raise an error if they pass any *args?

    def func(*args, **kwargs):
      if args:
        raise TypeError("no positional args allowed")
      arg1 = kwargs.pop("arg1", "default")
      if kwargs:
        raise TypeError("unknown args " + str(kwargs.keys()))
    

    It'd be simple to factor it into taking a list of varnames or a generic parsing function to use. It wouldn't be too hard to make this into a decorator (python 3.1), too:

    def OnlyKwargs(func):
      allowed = func.__code__.co_varnames
      def wrap(*args, **kwargs):
        assert not args
        # or whatever logic you need wrt required args
        assert sorted(allowed) == sorted(kwargs)
        return func(**kwargs)
    

    Note: i'm not sure how well this would work around already wrapped functions or functions that have *args or **kwargs already.

提交回复
热议问题