请教 type annotations 如何在运行时检查?

2017-10-09 16:11:46 +08:00
 aheadlead

对 Python 的 annotations 一直耿耿于怀,有些时候指定类型还是很便利的。

PEP 484 -- Type Hints 中有一段:

This PEP aims to provide a standard syntax for type annotations, opening up                           
Python code to easier static analysis and refactoring, potential runtime type
checking, and (perhaps, in some contexts) code generation utilizing type
information.

其中提到了 potential runtime type checking, 问题就在这,如何才能实现运行时检查类型。


(碎碎念:说来也怪,高中那年看到 python 不需要指定类型,一度震惊无比,
这么写了几年 python 后,觉得有的地方还是指定类型更合适)

2086 次点击
所在节点    Python
12 条回复
yonka
2017-10-09 16:14:19 +08:00
你的碎碎念是对的。
xrlin
2017-10-09 17:42:44 +08:00
用 assert ? 所以现在我又想用回编译型静态类型语言.
Kilerd
2017-10-09 17:46:56 +08:00
你需要 mypy
BBCCBB
2017-10-09 17:47:44 +08:00
you need mypy+1
ManjusakaL
2017-10-09 18:16:55 +08:00
运行时检查,inspect 库可以帮忙
aheadlead
2017-10-09 18:26:51 +08:00
@xrlin 我现在就是这么用的 写了几百行 assert 终于感觉我自己太 sb 了

@Kilerd
@BBCCBB 感谢!

@ManjusakaL 愿闻其详

此外,我还搜到了 enforce 和 typeguard 这俩玩意,不过上班没时间研究,有玩过的朋友可以讲讲吗?

https://github.com/RussBaz/enforce

https://github.com/agronholm/typeguard
xrlin
2017-10-09 19:40:36 +08:00
@aheadlead 什么时候出个 TypePython 就完美了。
ManjusakaL
2017-10-09 20:43:59 +08:00
@aheadlead 484 里面已经说了,annotation 是函数 signature 的一部分,inspect 是可以获取的
可以看看文档
https://docs.python.org/3/library/inspect.html#inspect.getfullargspec
ManjusakaL
2017-10-09 20:44:49 +08:00
而且楼上建议的 mypy 还是略废材,可以试试
https://github.com/google/pytype
huntzhan
2017-10-09 22:37:31 +08:00
我两年前写过一个运行时检查类型的: https://github.com/huntzhan/magic-constraints
不过我认为在 Python 里做类型检查价值不大
lolizeppelin
2017-10-10 15:46:31 +08:00
首先设计上要避免需要参数检查

一定要检查的的地方用装饰器模式实现会让代码简洁阅读性更好
lolizeppelin
2017-10-10 15:48:39 +08:00
inspect 的应用可以参考 openstack 里 taskflow 是怎么反射参数并处理的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/396201

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX