繁体   English   中英

如何运行多个函数直到一个函数返回 False?

[英]How to run through a number of functions until one returns False?

我希望score function 运行 while 循环,直到“检查”中的 1 个返回 False,如果没有返回 False,则退出循环。 “检查”还返回一个字符串,该字符串定义了我们将显示给用户的消息



def check_args(args, number_of_expected_args):
    if len(args) < number_of_expected_args:
        return False, 'cmd_missing_param'
    elif len(args) > number_of_expected_args:
        return False, 'cmd_extra_param'

def check_numbers(args, value):
    if args[value].isdigit() == False:
        return False, 'scores_invalid', 'var3'

def check_score(args, etc):
    if not blahblah....
        return False, 'response3'

def score(ctx, *args):

    test = []
    test[0], test[1] = True, 'Success'
    while test[0] == True:
        test = check_args(args, 4)
        test = check_numbers(args, 2)
        test = check_score(args, 3)
    
    print(test[1])

score(0, 1, 2, 3, 4)

这是我的工作代码的片段。 这是使用 discord.py 创建通道命令机器人,检查是为了验证附加到命令的 arguments。

这里定义了 2 个命令, scoreschedule ,它们都调用check_test function,尽管未来的命令可能只需要运行较少数量的检查。 所以我试图将每个单独的支票移到我较大的check_test function 之外,因为我将有更多的支票来定义并希望只能调用特定的支票

strings = {
    "english": {
        "cmd_missing_param": "Your submission is missing a parameter.",
        "cmd_extra_param": "Your submission has too many parameters.",
        "players_not_found": "Your submission user(s) {var1} cannot be found.",
        "scores_invalid": "Your submitted scores are not valid numbers.",
        "score_submitted": "Score successfully submitted",
        "schedule_submitted": "Schedule successfully submitted"
    }
}
    
async def reply(ctx, dict_string, arg1 = None, arg2 = None):
    # this function is to return a response to the user containing the success/fail message

    author = ctx.author.mention
    dict = strings['english']
    greeting = dict['greeting']
    response = dict[f'{dict_string}']

    return await ctx.reply(f"{greeting} {author}! {response}".format(var1 = arg1, var2 = arg2))

async def check_test(ctx, args, number_of_expected_args, args_players_index, args_scores_index, datetime_index, check_attachment):
    # this function is to perform a number of validations on our command args

    # check if command has expected number of args
    if args != '':
        if len(args) < number_of_expected_args:
            return False, 'cmd_missing_param'
        elif len(args) > number_of_expected_args:
            return False, 'cmd_extra_param'

    # check if the scores are valid numbers
    if args_scores_index != None:
        for each in args_scores_index:
            if args[each].isdigit() == False:
                return False, 'scores_invalid'
        
@client.command()
async def score(ctx, *args):
    # this command is to submit the score record for 2 players

    is_valid, response = await check_test(ctx, args, 4, [0, 1], [2, 3], None, '.w3g')
    if is_valid:
        player1, player2 = args[0], args[1]
        bot_message = await reply(ctx, 'score_submitted', player1, player2)
    else:
        await reply(ctx, response)
    
@client.command()
async def schedule(ctx, *args):
    is_valid, response = await check_test(ctx, args, 4, [0, 1], None, True, None)
    if is_valid: 
        player1, player2 = args[0], args[1]
        bot_message = await reply(ctx, 'schedule_submitted', player1, player2)
    else:
        await reply(ctx, response)

以下是您如何为args编写验证 function 的示例:

expected_number_of_args = 5


def validate_score_args(args):
    # example: test that exactly 'expected_number_of_args' were passed
    n = len(args)
    if n != expected_number_of_args:
        raise ValueError(f"Expected {expected_number_of_args} args, but got {n}.")

    # example: make sure all args are numeric
    if not all(type(arg) in {int, float} for arg in args):
        raise TypeError(f"Expected all arguments to be numeric.")

    # example: if the above test passed, then check values
    if not all(arg > 0 for arg in args):
        raise ValueError(f"Expected all arguments to be positive.")

    # and so on


def score(ctx, *args):
    try:
        validate_score_args(args)
    except (ValueError, TypeError) as err:
        # Do something about error instead of 're-raising' it, but for now:
        raise err
    
    # If args were valid, then use them:
    return sum(args)

添加任意数量的“测试”到validate_score_args() 它们将按从上到下的顺序运行,如果任何测试失败,则不会运行以下任何测试。

但是,我建议始终运行所有测试,然后“收集”所有错误并对其进行处理(例如将它们显示给用户),以便用户可以立即看到他们做错的所有事情,而不必玩打地鼠,一次修复一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM