如何检查是否使用检查功能设置了python函数参数的默认值?

问题描述

我正在尝试识别未设置认值的函数的参数。我正在使用inspect.signature(func).parameters.value()函数,该函数提供了函数参数列表。由于我使用的是PyCharm,因此可以看到未设置认值的参数的Parameter.default属性设置为inspect._empty。我以以下方式声明该功能

def f(a,b=1):
    pass

因此,a认值为inspect._empty。由于inspect._empty是私有属性,因此我认为可能存在一种检查值是否为inspect._empty方法,但找不到它。

解决方法

您可以这样做:

@kick.error
async def on_kick_error(ctx,error):
    if isinstance(error,commands.MissingRequiredArgument):
        await ctx.send('Please specify an user')
    elif isinstance(error,commands.CheckFailure):
        await ctx.send('You do not have a perms to do that!')
    else:
        await ctx.send('There is some error')

输出:

import inspect


def foo(a,b=1):
    pass


for param in inspect.signature(foo).parameters.values():
    if param.default is param.empty:
        print(param.name)

a 拥有相同的对象param.empty。我想由于official documentation of inspect module中的示例,建议使用这种使用方式:

inspect._empty