栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python 3和静态类型

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 3和静态类型

感谢您阅读我的代码!

确实,在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 israised 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 syslog = printdef 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 valuedef 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 newfdef 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

关于此问题的可能解决方案,还有很多要说的,但是强制执行“计算机类型”显然只是解决方案的一半,因此,至少在我看来,这 比根本没有解决方案还要糟糕
。这也是为什么 Systems Hungarian 是一个糟糕的主意,而 Apps Hungarian 是一个很棒的主意的原因。
乔尔·斯波斯基(Joel
Spolsky)的
信息量非常丰富。

现在,如果有人要实现某种Pythonic第三方库,该库将自动将其 人类类型 分配给现实数据,然后小心地将其转换为类似类型

width *height -> area
并使用功能注释强制执行该检查,那么我认为这将是一种类型检查人真的可以使用!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669268.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号