python 中的装饰器安全功能
Functions decorator safety in python
这段代码是如何工作的?它来自渐变 "Data Science by Scratch" 中的第 8 章。为什么我需要将一个函数包装在另一个函数中?有没有更易读的方法来实现这种异常处理?这是对它的解释。
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
您缺少函数调用:
假设我定义了这样一个平均函数:
def naive_average(lst):
return float(sum(lst))/len(lst)
如果 lst
为空会怎样?或者它是否包含非数字的内容?
砰,异常!
使用你提到的装饰器,函数看起来像这样
@safe
def naive_average(lst):
return float(sum(lst))/len(lst)
现在,在空 lst
上调用它会 return float('inf')
而不是异常
假设我们有一个像这样的简单函数:
def myfunc(n):
return 42/n
我们这样做:
print(myfunc(0))
我们得到这个:
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
现在我们这样做:
myfunc = safe(myfunc)
print(myfunc(0))
我们得到这个:
inf
我们第二次调用 safe()
,其中 returns 是一个具有嵌入式异常处理的新函数。我们替换了 name "myfunc" 所指的内容,现在它指的是返回的函数。原来的myfunc
没丢,新里面叫f
@safe
装饰器本质上与 myfunc = safe(myfunc)
做同样的事情
这段代码是如何工作的?它来自渐变 "Data Science by Scratch" 中的第 8 章。为什么我需要将一个函数包装在另一个函数中?有没有更易读的方法来实现这种异常处理?这是对它的解释。
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
您缺少函数调用:
假设我定义了这样一个平均函数:
def naive_average(lst):
return float(sum(lst))/len(lst)
如果 lst
为空会怎样?或者它是否包含非数字的内容?
砰,异常!
使用你提到的装饰器,函数看起来像这样
@safe
def naive_average(lst):
return float(sum(lst))/len(lst)
现在,在空 lst
上调用它会 return float('inf')
而不是异常
假设我们有一个像这样的简单函数:
def myfunc(n):
return 42/n
我们这样做:
print(myfunc(0))
我们得到这个:
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
现在我们这样做:
myfunc = safe(myfunc)
print(myfunc(0))
我们得到这个:
inf
我们第二次调用 safe()
,其中 returns 是一个具有嵌入式异常处理的新函数。我们替换了 name "myfunc" 所指的内容,现在它指的是返回的函数。原来的myfunc
没丢,新里面叫f
@safe
装饰器本质上与 myfunc = safe(myfunc)