感谢您阅读我的代码!
确实,在Python中创建通用注释执行器并不难。这是我的看法:
'''Very simple enforcer of type annotations.
This toy super-decorator can decorate all functions in a given module that have
annotations so that the type of input and output is enforced; an AssertionError is
raised on mismatch.
This module also has a test function func() which should fail and logging facility
log which defaults to print.
Since this is a test module, I cut corners by only checking *keyword* arguments.
'''
import sys
log = print
def func(x:'int' = 0) -> 'str':
'''An example function that fails type checking.'''
return x
# For simplicity, I only do keyword args.
def check_type(*args):
param, value, assert_type = args
log('Checking {0} = {1} of {2}.'.format(*args))
if not isinstance(value, assert_type):
raise AssertionError(
'Check Failed - parameter {0} = {1} not {2}.'
.format(*args))
return value
def decorate_func(func):
def newf(*args, **kwargs):
for k, v in kwargs.items():
check_type(k, v, ann[k])
return check_type('<return_value>', func(*args, **kwargs), ann['return'])
ann = {k: eval(v) for k, v in func.__annotations__.items()}
newf.__doc__ = func.__doc__
newf.__type_checked = True
return newf
def decorate_module(module = '__main__'):
'''Enforces type from annotation for all functions in module.'''
d = sys.modules[module].__dict__
for k, f in d.items():
if getattr(f, '__annotations__', {}) and not getattr(f, '__type_checked', False):
log('Decorated {0!r}.'.format(f.__name__))
d[k] = decorate_func(f)
if __name__ == '__main__':
decorate_module()
# This will raise AssertionError.
func(x = 5)
鉴于这种简单性,乍一看这东西不是主流很奇怪。但是,我相信有充分的理由说明它 。通常,类型检查会有所帮助,因为如果添加整数和字典,很可能会犯一些明显的错误(并且如果您要讲的是合理的话, 显式要比隐式好 。
但是在现实生活中,您经常会混合使用与编译器所见的 相同但数量明显不同的 ,例如,以下代码段包含一个明显的错误:
height = 1.75 # Bob's height in meters.
length = len(sys.modules) # Number of modules imported by program.
area = height * length # What's that supposed to mean???
任何人应立即看到上面的行了一个错误,只要它知道变量的“人型”height
和length
即使它看起来计算机 的乘法int
和float
。
关于此问题的可能解决方案,还有很多要说的,但是强制执行“计算机类型”显然只是解决方案的一半,因此,至少在我看来,这 比根本没有解决方案还要糟糕 。这也是为什么 是一个糟糕的主意,而 是一个很棒的主意的原因。 信息量非常丰富。
现在,如果有人要实现某种Pythonic第三方库,该库将自动将其 分配给现实数据,然后小心地将其转换为类似类型width * height -> area
并使用功能注释强制执行该检查,那么我认为这将是一种类型检查人真的可以使用!