PyContracts is a Python package that allows to declare constraints on function parameters and return values. Contracts can be specified using Python3 annotations, or inside a docstring. PyContracts supports a basic type system, variables binding, arithmetic constraints, and has several specialized contracts and an extension API.
import time
from contracts import contract
@contract(a='int,>0', b='list[N],N>0', returns='list[N]')
def c(a, b):
return [a * i for i in b]
def d(a, b):
assert isinstance(a, int)
assert a > 0
assert isinstance(b, list)
assert len(b) > 0
out = [a * i for i in b]
assert len(out) == len(b)
return out
tic = time.time()
x = list(range(100))
for i in range(1000):
x = c(5, x)
tic2 = time.time()
print(tic2-tic)
x = list(range(100))
for i in range(1000):
x = d(5, x)
tic3 = time.time()
print(tic3-tic2)
I tested this on my machine
Found the result to be
Are there any additional checks that are missing in my manual implementation?