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

2024-03-29 09:08:54 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以用以下函数编写合同

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

    """

还要检查idx<len?你知道吗

语言参考页http://andreacensi.github.io/contracts/reference.html#contracts-language-reference的“算术和比较”部分还有待编写。你知道吗


Tags: 函数语言httpindexlenparamdeftype
1条回答
网友
1楼 · 发布于 2024-03-29 09:08:54

比赛有点晚了,但我有同样的问题,我发现:

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

对任何其他有同样想法的人来说。您可以在契约中使用变量并引用它们。你知道吗

相关问题 更多 >