[英]Elegant way to check arguments across multiple functions
I'm working on some python code which includes a large number of functions.我正在处理一些包含大量函数的 python 代码。 Many of these require the same set of input arguments.
其中许多需要相同的输入参数集。
I need to place some restrictions on the values of the input arguments.我需要对输入参数的值进行一些限制。 If they lie outside some prescribed range then I want to raise an error message.
如果它们位于某个规定范围之外,那么我想提出一条错误消息。 Ideally, I'd like to do this without lots of repeated code.
理想情况下,我希望在没有大量重复代码的情况下执行此操作。 Below is a simplified example of what I'm trying to do:
下面是我正在尝试做的一个简化示例:
def check_positive(T):
# Temperatures must be provided in kelvin
if T < 0:
print('Temperatures are in K, negative values not allowed!')
def double(T):
check_positive(T)
return 2*T
def treble(T):
check_positive(T)
return 3*T
T = -2
print(double(T))
T = 100
print(treble(T))
In my implementation, each function will need to call the check_positive function.在我的实现中,每个函数都需要调用 check_positive 函数。 Is there a more elegant way of achieving the same behavior in python?
是否有更优雅的方式在 python 中实现相同的行为?
Sounds like the perfect use-case for python decorators !听起来像是python 装饰器的完美用例!
Edit:编辑:
from functools import wraps
def check_positive(func):
@wraps(func)
def wrapper(*T):
# Temperatures must be provided in kelvin
if T[0] < 0:
print('Temperatures are in K, negative values not allowed!')
raise ValueError # optional
return func(T[0])
return wrapper
@check_positive
def double(T):
return 2*T
...
A decorator can be used here:可以在此处使用装饰器:
def check_positive(func):
def wrapper(*args, **kw):
if args[0] < 0:
print('Temperatures are in K, negative values not allowed!')
return func(*args, **kw)
return wrapper
@check_positive
def double(T):
return 2*T
@check_positive
def treble(T):
return 3*T
T = -2
print(double(T))
T = 100
print(treble(T))
Output:输出:
Temperatures are in K, negative values not allowed!
-4
300
You could change the decorator further to return an exception if a negative value was passed - here we just print the statement as in your example.如果传递了负值,您可以进一步更改装饰器以返回异常 - 在这里我们只打印您的示例中的语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.