通过检查程序运行来推断类型
项目描述
Farthing可以在给定文件或目录中运行任意Python代码,同时跟踪其中所有函数的参数和返回类型。Farthing可以根据执行过程中观察到的值类型自动添加类型注解。如果您想为现有的Python代码添加静态类型,或者探索不确定值类型的代码库,这可能很有用。
例如,以下代码
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
可以通过运行Farthing针对以下测试文件自动转换为
def factorial(n: int) -> int:
result = 1
for i in range(2, n + 1):
result *= i
return result
使用Farthing运行以下测试文件
from nose.tools import assert_equal
import fact
def test_fib():
test_cases = [
(0, 1),
(1, 1),
(2, 2),
(3, 6),
(4, 24),
(5, 120),
]
for index, value in test_cases:
yield _check_fact, index, value
def _check_fact(index, value):
assert_equal(value, fact.factorial(index))
用法
Farthing可以从命令行调用。第一个参数应该是应该添加类型注解的文件或目录。其他参数应该是运行Python脚本的任何参数。例如
farthing demo/fact.py _virtualenv/bin/nosetests demo/tests.py
演示
要运行演示,只需运行demo.sh。为了解释它实际上做什么
运行make bootstrap来设置带有依赖项的虚拟环境。
运行. _virtualenv/bin/activate进入虚拟环境。
运行farthing demo/fact.py _virtualenv/bin/nosetests demo/tests.py来运行_virtualenv/bin/nosetests demo/tests.py并基于执行运行中使用的实际值类型,为demo/fact.py添加注解。
限制
目前,Farthing只是一个快速原型,因此目前有以下限制
注解仅使用类型名称添加,这可能在当前作用域中不可用。
无法向正在运行的Python脚本添加类型注解。
使用第一个看到的类型,而不是尝试找到超类型。
我非常想看到类似的项目,如果您知道任何,如果您能让我知道,我将不胜感激。