簡體   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