I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: Is there a way to programatically list the keyword arguments the a specific function takes?推荐答案比直接检查代码对象并计算变量要好得多的方法是使用inspect模块.A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.>>> import inspect>>> def func(a,b,c=42, *args, **kwargs): pass>>> inspect.getargspec(func)(['a', 'b', 'c'], 'args', 'kwargs', (42,))如果您想知道它是否可以与一组特定的args一起调用,则需要未指定默认值的args.这些可以通过以下方式获得:If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:def getRequiredArgs(func): args, varargs, varkw, defaults = inspect.getargspec(func) if defaults: args = args[:-len(defaults)] return args # *args and **kwargs are not required, so ignore them.然后一个函数来告诉您特定字典中缺少的内容是:Then a function to tell what you are missing from your particular dict is:def missingArgs(func, argdict): return set(getRequiredArgs(func)).difference(argdict)类似地,要检查无效的参数,请使用:Similarly, to check for invalid args, use:def invalidArgs(func, argdict): args, varargs, varkw, defaults = inspect.getargspec(func) if varkw: return set() # All accepted return set(argdict) - set(args)因此可调用的完整测试是:And so a full test if it is callable is :def isCallableWithArgs(func, argdict): return not missingArgs(func, argdict) and not invalidArgs(func, argdict)(这仅对python的arg解析是有好处的.任何运行时检查kwargs中的无效值显然都无法检测到.)(This is good only as far as python's arg parsing. Any runtime checks for invalid values in kwargs obviously can't be detected.) 这篇关于您可以列出函数接收的关键字参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-06 09:04