【问题标题】:Error Handling without using try/except in a Python Function在 Python 函数中不使用 try/except 的错误处理
【发布时间】:2016-04-06 08:35:06
【问题描述】:

我写了这个 python 函数。项目规范不允许我使用 try/except 来处理错误。根据文档字符串,如果成功,我应该返回 False,如果失败,则返回 True,我将调用 declare_error 函数。在 main 函数中处理的行号。

注意,除了 sys 和 os,我不允许导入任何东西,所以使用正则表达式是不可能的。

这是我的代码。关于 if/else 语句我应该使用什么的任何建议?

#===============================================================================
def read_subsequent_lines(file_object, line_number, simulation_obj_list):
#===============================================================================
     '''Read and parse the next line of the file, confirm it matches one of the
        line signatures, such as ('sim_object_type=World', 'size=')

        Parameters: file_object, the input file object.
                    line_number, the current line number being read in.
                    simulation_obj_list, the list of converted lines.
        Returns: False for success, True for failure

        Convert the line in the file to a list of strings, with one string per
            name=value pair (such as "name=Joe").  Make sure that each line matches
            up with one of the line "signatures" in the constant definitions.
            Modify this line_list to only include the value portion of the pair,
            calling extract_line_using_signature (...) to get the each line list.
            Append each modified line_list to the simulation_obj_list( ).

        If success: Return False.
        If failure: Call declare_error (...) and Return True.
    '''
    #List of lists to contain each line of the input file
    line_list = []
    #Read in Lines and append to a list of lines containing strings
    for line in file_object:
        # print(line.strip().split(','))
        line_list.append(line.strip().split())

    #Compare line to signature constants and append to simulation_obj_list
    for i in line_list:
        #World
        if len(i) == NUM_WORLD_TOKENS:
            if i[0].startswith(LINE_SIGNATURE_TUPLE[0][0]) and i[1].startswith(LINE_SIGNATURE_TUPLE[0][1]):
                 simulation_obj_list.append(extract_line_using_signature(LINE_SIGNATURE_TUPLE[0],i))
        #Person
        if len(i) == NUM_PERSON_TOKENS:
            if i[0].startswith(LINE_SIGNATURE_TUPLE[1][0]) and i[1].startswith(LINE_SIGNATURE_TUPLE[1][1]) and \
                i[2].startswith(LINE_SIGNATURE_TUPLE[1][2]):
                    simulation_obj_list.append(extract_line_using_signature(LINE_SIGNATURE_TUPLE[1],i))
        #Robot
        if len(i) == NUM_ROBOT_TOKENS:
            if i[0].startswith(LINE_SIGNATURE_TUPLE[2][0]) and i[1].startswith(LINE_SIGNATURE_TUPLE[2][1]) and \
                i[2].startswith(LINE_SIGNATURE_TUPLE[2][2]) and i[3].startswith(LINE_SIGNATURE_TUPLE[2][3]):
                simulation_obj_list.append(extract_line_using_signature(LINE_SIGNATURE_TUPLE[2],i))

【问题讨论】:

    标签: python error-handling


    【解决方案1】:

    快速丑陋的解决方法是使用elifs 和elses(我假设NUM_WORLD_TOKENSNUM_PERSON_TOKENSNUM_ROBOT_TOKENS 都是唯一值):

    #Compare line to signature constants and append to simulation_obj_list
    for i in line_list:
        #World
        if len(i) == NUM_WORLD_TOKENS:
            if i[0].startswith(LINE_SIGNATURE_TUPLE[0][0]) and i[1].startswith(LINE_SIGNATURE_TUPLE[0][1]):
                 simulation_obj_list.append(extract_line_using_signature(LINE_SIGNATURE_TUPLE[0],i))
            else:
                declare_error()
                return True
        #Person
        elif len(i) == NUM_PERSON_TOKENS:
            if i[0].startswith(LINE_SIGNATURE_TUPLE[1][0]) and i[1].startswith(LINE_SIGNATURE_TUPLE[1][1]) and \
                i[2].startswith(LINE_SIGNATURE_TUPLE[1][2]):
                    simulation_obj_list.append(extract_line_using_signature(LINE_SIGNATURE_TUPLE[1],i))
            else:
                declare_error()
                return True
        #Robot
        elif len(i) == NUM_ROBOT_TOKENS:
            if i[0].startswith(LINE_SIGNATURE_TUPLE[2][0]) and i[1].startswith(LINE_SIGNATURE_TUPLE[2][1]) and \
                i[2].startswith(LINE_SIGNATURE_TUPLE[2][2]) and i[3].startswith(LINE_SIGNATURE_TUPLE[2][3]):
                simulation_obj_list.append(extract_line_using_signature(LINE_SIGNATURE_TUPLE[2],i))
            else:
                declare_error()
                return True
    
        return False
    

    不过那是很臭的代码。使用正则表达式怎么样?

    for line in lines:
        if re.match(WORLD_REGEX, line):
            simulation_obj_list.append(
                extract_line_using_signature(LINE_SIGNATURE_TUPLE[0], line))
        elif re.match(PERSON_REGEX, line):
            # etc
    
        else:
            declare_error()
            return True
    
        return False
    

    【讨论】:

    • 啊,太糟糕了。但是您应该仍然可以使用我发布的第一个代码。我也很好奇你所说的 Line number taken care of in a main function. 是什么意思 在 for 循环中使用 enumerate 将免费为你提供行号。
    • 很遗憾,我的导师要求我们使用入门代码。所以line_number在main函数中是递增的,并且只在read_subsequent_lines中声明和出错时使用。教授还拒绝我使用正则表达式,因为他对 Python 比较陌生,自己也没有使用过。
    • 那是个糟糕的教练。我的第一个解决方案对您有帮助吗?
    • 您在main 中究竟是如何调用read_subsequent_lines 的?你是在文件中的每一行调用一次吗?
    • 我之前说过谢谢,这很有帮助。我的意思是说谢谢你的帮助。我自己找到了一个解决方案,并在收到您的回复之前提交了该项目,因为它已经到期了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多