我可以使用pycontracts来比较两个参数的值吗?

时间:2014-05-20 21:08:34

标签: python

是否可以在以下函数中编写合同

def func(len, idx):
    """
    :param len: array length
    :type len: int,>0
    :param idx: array index
    :type idx: int,>=0

    """

还要检查idx<len

&#34;算术和比较&#34;语言参考页面http://andreacensi.github.io/contracts/reference.html#contracts-language-reference的部分尚未编写。

1 个答案:

答案 0 :(得分:0)

游戏进行得有点晚,但是我有同样的问题,这是我发现的:

In [10]: @contract(offset="int,>0,N", limit="(int,>=N)|None") 
...: def test(offset,limit,): 
...:     print(offset,limit) 
In [13]: test(1, 1)
1 1
In [14]: test(1, 0)
---------------------------------------------------------------------------
ContractNotRespected                      Traceback (most recent call last)
# SNIP THE STACK
ContractNotRespected: Breach for argument 'limit' to test().
Could not satisfy any of the 2 clauses in int,>=N|None.
 ---- Clause #1:   int,>=N
 | Condition 0 >= 1 not respected
 | checking: >=N       for value: Instance of <class 'int'>: 0   
 | checking: int,>=N   for value: Instance of <class 'int'>: 0   
 | Variables bound in inner context:
 | - N: Instance of <class 'int'>: 1
 ---- Clause #2:   None
 | Value does not pass criteria of is_None()() (module: contracts.library.miscellaneous_aliases).
 | checking: callable()   for value: Instance of <class 'int'>: 0   
 | checking: None         for value: Instance of <class 'int'>: 0   
 | Variables bound in inner context:
 | - N: Instance of <class 'int'>: 1
  ------- (end clauses) -------
 checking: int,>=N|None   for value: Instance of <class 'int'>: 0   
 Variables bound in inner context:
 - N: Instance of <class 'int'>: 1
 In [15]: test(1, 2)                                                                                                                               
 1 2

对于任何其他想知道同一件事的人。您可以在合同中使用变量并对其进行引用。