如何使用 Python 装饰器检查函数参数? [英] How to use Python decorators to check function arguments?
本文介绍了如何使用 Python 装饰器检查函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想定义一些通用装饰器来在调用一些函数之前检查参数.
I would like to define some generic decorators to check arguments before calling some functions.
类似于:
@checkArguments(types = ['int', 'float'])
def myFunction(thisVarIsAnInt, thisVarIsAFloat)
''' Here my code '''
pass
附注:
- 类型检查只是为了展示一个例子
- 我使用的是 Python 2.7,但 Python 3.0 也应该很有趣
推荐答案
Python 2
def accepts(*types):
def check_accepts(f):
assert len(types) == f.func_code.co_argcount
def new_f(*args, **kwds):
for (a, t) in zip(args, types):
assert isinstance(a, t), \
"arg %r does not match %s" % (a,t)
return f(*args, **kwds)
new_f.func_name = f.func_name
return new_f
return check_accepts
Python 3
在 Python 3 中 func_code
已更改为 __code__
并且 func_name
已更改为 __name__
.
In Python 3 func_code
has changed to __code__
and func_name
has changed to __name__
.
def accepts(*types):
def check_accepts(f):
assert len(types) == f.__code__.co_argcount
def new_f(*args, **kwds):
for (a, t) in zip(args, types):
assert isinstance(a, t), \
"arg %r does not match %s" % (a,t)
return f(*args, **kwds)
new_f.__name__ = f.__name__
return new_f
return check_accepts
用法:
@accepts(int, (int,float))
def func(arg1, arg2):
return arg1 * arg2
func(3, 2) # -> 6
func('3', 2) # -> AssertionError: arg '3' does not match <type 'int'>
arg2
可以是 int
或 float
arg2
can be either int
or float
这篇关于如何使用 Python 装饰器检查函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文