可以使用Python try/ except 函数来规则所有这些(使用不同的输入)吗?

发布于 2025-01-12 06:49:03 字数 456 浏览 0 评论 0原文

我试图在 Python 中定义一个可以处理各种其他函数的 try/ except 函数。 这个想法就是这样的:

def func1(x,y):
    z = x+y
    return z
    
def error_check(func1):
    try: stuff = func1()
    except: 
        print('Error')     
    return stuff
    
error_check(func1('1',2))

在这种情况下,对于这些输入,error_check 函数甚至不起作用。 目的是我可以将 error_check 与另一个具有不同数量输入的 func2 一起使用。例如:

def func2(w,x,y):
    z = w+x+y
    return z

这可能吗?

多谢

I'm trying to define in Python a try/except function that can handle various other function.
The idea is quite this one:

def func1(x,y):
    z = x+y
    return z
    
def error_check(func1):
    try: stuff = func1()
    except: 
        print('Error')     
    return stuff
    
error_check(func1('1',2))

In this case, with those inputs, the error_check function doesn't even work.
The aim is that I can use error_check with another func2 with a diverse number of inputs. For examples:

def func2(w,x,y):
    z = w+x+y
    return z

Is that possible?

Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扭转时空 2025-01-19 06:49:03

整个想法的核心问题是捕获错误并不意味着您修复了错误。只需使用引发异常的 func1 尝试您的函数,您就会看到问题:

>>> def error_check(func1):
...     try:
...         stuff = func1()
...     except:
...         print('Error')
...     return stuff
...
>>> def oops():
...     raise ValueError
...     print("Computing the answer...")
...     return 42
...
>>> error_check(oops)
Error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in error_check
UnboundLocalError: local variable 'stuff' referenced before assignment

请注意,我们在输出中看不到 Computing the answer...,而我们的函数不返回 42! 我们在 error_check 中无法做任何事情来改变这一点。

问题是,如果 func1 引发异常,它不会返回任何内容。因此没有东西可以返回。您不能通过忽略函数引发的异常来强制函数“工作”;如果一个函数引发异常,则意味着它无法完成它应该做的事情

也许您对此表示同意,并希望您的 error_check 返回 None 而不是 func1 应该返回的内容。如果是这样,您可以这样做:

def error_check(func1):
    try:
        return func1()
    except Exception as e:
        print(f"Error")

如果出现异常,这将隐式返回 None。它不会引发另一个异常,但 func1 仍然不会做它应该做的事情:

>>> error_check(oops)
Error
>>>

请注意,如果我们需要 42 值来做其他事情在我们的程序中,那个现在可能会引发错误,如果您捕获该错误,那么之后的事物将会引发错误,依此类推,并且很快。最终,仅仅发现错误并忽略它们不会给自己带来任何好处。

话虽如此,如果您希望能够将其他参数传递给 func1,请使用 *args**kwargs

def error_check(func1, *args, **kwargs):
    try:
        return func1(*args, **kwargs)
    except Exception as e:
        print(f"Error: {e}")

现在您可以这样做:

error_check(func1, '1', 2)

func1 将在 error_check 内调用,*args('1', 2)

The core problem with this whole idea is that catching an error doesn't mean you fixed the error. Just try your function with a func1 that raises an exception and you'll see the problem:

>>> def error_check(func1):
...     try:
...         stuff = func1()
...     except:
...         print('Error')
...     return stuff
...
>>> def oops():
...     raise ValueError
...     print("Computing the answer...")
...     return 42
...
>>> error_check(oops)
Error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in error_check
UnboundLocalError: local variable 'stuff' referenced before assignment

Note that we don't see Computing the answer... in the output, and our function does not return 42! There is nothing we can do in error_check that will change this.

The problem is that if func1 raises an exception, it does not return anything. Hence there is no stuff to return. You can't force a function to "work" by just ignoring the exception it raises; if a function raises an exception, it means it could not do the thing it was supposed to do.

Maybe you're okay with this and want your error_check to return None instead of whatever func1 was supposed to return. If so, you could do:

def error_check(func1):
    try:
        return func1()
    except Exception as e:
        print(f"Error")

This will implicitly return None if there's an exception. It won't raise another exception, but func1 is still not going to do the thing that it was supposed to do:

>>> error_check(oops)
Error
>>>

Note that if we needed that 42 value for something else in our program, that thing is now probably going to raise an error, and if you catch that error, the thing after it will raise an error, and so on, and so on. Ultimately, you don't do yourself any favors by just catching errors and ignoring them.

All that said, if you want to be able to pass other arguments to func1, use *args and **kwargs:

def error_check(func1, *args, **kwargs):
    try:
        return func1(*args, **kwargs)
    except Exception as e:
        print(f"Error: {e}")

Now you can do:

error_check(func1, '1', 2)

and func1 will be called within error_check with *args of ('1', 2).

や莫失莫忘 2025-01-19 06:49:03

您的问题是,在最后一行中,您实际上是在调用 func1 ,然后对结果调用 error_check 。请尝试这样的操作,其中 lambda 会延迟求值,直到 try 块出现,就像我们想要的那样:

def func1(x,y):
    z = x+y
    return z
    
def error_check(func1):
    try:
        stuff = func1()
        return stuff
    except: 
        print('Error')     
        return None
    
error_check(lambda: func1('1',2))

您还会遇到一个错误,因为 stuff 未定义如果 try 块失败,那么我就冒昧地修复了这个问题。

Your issue is that in the last line there, you are actually calling func1 and then calling error_check on the result. Try something like this instead, where the lambda delays evaluation until the try block like we want:

def func1(x,y):
    z = x+y
    return z
    
def error_check(func1):
    try:
        stuff = func1()
        return stuff
    except: 
        print('Error')     
        return None
    
error_check(lambda: func1('1',2))

You also have an error in that stuff is undefined if the try block failed, so I took the liberty of fixing that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文