
对 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 后,觉得有的地方还是指定类型更合适)
1 yonka Oct 9, 2017 你的碎碎念是对的。 |
2 xrlin Oct 9, 2017 用 assert ? 所以现在我又想用回编译型静态类型语言. |
3 Kilerd Oct 9, 2017 你需要 mypy |
4 BBCCBB Oct 9, 2017 you need mypy+1 |
5 ManjusakaL Oct 9, 2017 运行时检查,inspect 库可以帮忙 |
6 aheadlead OP @xrlin 我现在就是这么用的 写了几百行 assert 终于感觉我自己太 sb 了 @Kilerd @BBCCBB 感谢! @ManjusakaL 愿闻其详 此外,我还搜到了 enforce 和 typeguard 这俩玩意,不过上班没时间研究,有玩过的朋友可以讲讲吗? https://github.com/RussBaz/enforce https://github.com/agronholm/typeguard |
8 ManjusakaL Oct 9, 2017 @aheadlead 484 里面已经说了,annotation 是函数 signature 的一部分,inspect 是可以获取的 可以看看文档 https://docs.python.org/3/library/inspect.html#inspect.getfullargspec |
9 ManjusakaL Oct 9, 2017 而且楼上建议的 mypy 还是略废材,可以试试 https://github.com/google/pytype |
10 huntzhan Oct 9, 2017 我两年前写过一个运行时检查类型的: https://github.com/huntzhan/magic-constraints 不过我认为在 Python 里做类型检查价值不大 |
11 lolizeppelin Oct 10, 2017 via Android 首先设计上要避免需要参数检查 一定要检查的的地方用装饰器模式实现会让代码简洁阅读性更好 |
12 lolizeppelin Oct 10, 2017 via Android inspect 的应用可以参考 openstack 里 taskflow 是怎么反射参数并处理的 |