从python中的函数返回错误字符串 [英] Returning error string from a function in python

查看:31
本文介绍了从python中的函数返回错误字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个类函数,它返回成功或失败,但如果失败,我希望它返回一个特定的错误字符串.我有 3 种方法:

I have a class function in Python that either returns a success or a failure, but in case of a failure I want it to send a specific error string back. I have 3 approaches in mind:

  1. 将变量 error_msg 传递给最初设置为 None 的函数,如果出现错误,则将其设置为错误字符串.例如:

  1. Pass in an variable error_msg to the function originally set to None and in case of an error, it gets set to the error string. eg:

if !(foo(self, input, error_msg)):
    print "no error"
else:
    print error_msg

  • 从函数返回一个包含 bool 和 error_msg 的元组.

  • Return a tuple containing a bool and error_msg from the function.

    我在发生错误时引发异常并在调用代码中捕获它.但由于我没有看到我正在处理的代码库中经常使用异常,所以不太确定是否采用这种方法.

    I raise an exception in case of an error and catch it in the calling code. But since I don't see exceptions being used often in the codebase I am working on, so was not too sure about taking this approach.

    这样做的 Pythonic 方式是什么?

    What is the Pythonic way of doing this?

    推荐答案

    创建您自己的异常并引发该异常:

    Create your own exception and raise that instead:

    class MyValidationError(Exception):
        pass
    
    def my_function():
        if not foo():
            raise MyValidationError("Error message")
        return 4
    

    然后你可以调用你的函数:

    You can then call your function as:

    try:
        result = my_function()
    except MyValidationError as exception:
        # handle exception here and get error message
        print exception.message
    

    这种风格称为 EAFP(请求宽恕比许可更容易"),这意味着您可以照常编写代码,在出现问题时引发异常并稍后处理:

    This style is called EAFP ("Easier to ask for forgiveness than permission") which means that you write the code as normal, raise exceptions when something goes wrong and handle that later:

    这个常见的Python编码风格假定存在有效的键或属性,并且如果假设证明为假,则捕获异常.这种干净和快速风格的特点是存在许多尝试和例外声明.该技术与许多人常见的 LBYL 风格形成鲜明对比.其他语言,如 C.

    This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

    这篇关于从python中的函数返回错误字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆