简体   繁体   English

Python中的函数装饰器安全性

[英]Functions decorator safety in python

How this code works? 该代码如何工作? It is from chapter 8 in "Data Science by Scratch" from the gradient. 它来自梯度的“数据科学,从零开始”的第8章。 Why do I need to wrap a function inside another fucntion? 为什么我需要在另一个函数中包装一个函数? Is there a more readable way to achieve this execption handling? 有没有更可读的方法来实现这种执行处理? Here's the explanation for it. 这是它的解释。

It is possible that certain step sizes will result in invalid inputs for our function. 某些步长可能会导致我们的功能输入无效。 So we'll need to create a “safe apply” function that returns infinity (which should never be the minimum of anything) for invalid inputs: 因此,我们需要创建一个“安全应用”函数,以对无效输入返回无穷大(永远不应为最小):

def safe(f):
    """return a new function that's the same as f,
    except that it outputs infinity whenever f produces an error"""
    def safe_f(*args, **kwargs):
        try:
             return f(*args, **kwargs)
        except:
             return float('inf')
    return safe_f

You are missing the function call: 您缺少函数调用:

Lets say I define an average function like this: 可以说我定义了一个平均函数,如下所示:

def naive_average(lst):
    return float(sum(lst))/len(lst)

What would happen if lst is empty ? 如果lst为空会怎样? or if it contains something that isn't numeric ? 还是包含非数字内容? BOOM, exception ! BOOM,例外!

With the decorator you mentioned, the function would look like this 使用您提到的装饰器,该函数将如下所示

@safe
def naive_average(lst):
    return float(sum(lst))/len(lst)

and now, calling it on an empty lst would return float('inf') instead of an exception 现在,在空的lst上调用它会返回float('inf')而不是异常

Lets say we have a trivial function like this: 可以说我们有一个琐碎的函数,像这样:

def myfunc(n):
    return 42/n

and we do this: 我们这样做:

print(myfunc(0))

We get this: 我们得到这个:

Traceback (most recent call last):
  File "gash.py", line 14, in <module>
    print(myfunc(0))
  File "gash.py", line 12, in myfunc
    return 42/n
ZeroDivisionError: division by zero

Now we do this: 现在我们这样做:

myfunc = safe(myfunc)
print(myfunc(0))

We get this: 我们得到这个:

inf

The second time we call safe() which returns a new function with the embedded exception handling. 第二次我们调用safe() ,它返回带有嵌入式异常处理的新函数。 We replace what the name "myfunc" refers to, now it refers to the returned function. 我们替换了名称 “ myfunc”所指的内容,现在它指的是返回的函数。 The original myfunc is not lost, it is called f inside the new one. 原来的myfunc不会丢失,它在新的myfunc中被称为f

A @safe decorator is essentially doing the same thing as myfunc = safe(myfunc) @safe装饰器实际上与myfunc = safe(myfunc)做相同的事情

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

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