Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyContract检查导入模块中的函数_Python_Design By Contract - Fatal编程技术网

Python PyContract检查导入模块中的函数

Python PyContract检查导入模块中的函数,python,design-by-contract,Python,Design By Contract,我正在使用(不是)为我的遗传算法框架实现契约式设计 主要模块是GA.py,它从crossover.py调用函数(我们称之为foocross)。我已经为foocross编写了前置条件和后置条件表达式 现在,我希望在GA.py中运行main时检查这些条件。我在foocross中引入了一个假前提条件,只是为了测试合同是否被检查,但似乎没有。如何确保检查合同 下面是我的代码的一小部分: # GA.py def main(): # some code crossover.foocross(

我正在使用(不是)为我的遗传算法框架实现契约式设计

主要模块是
GA.py
,它从
crossover.py
调用函数(我们称之为
foocross
)。我已经为
foocross
编写了前置条件和后置条件表达式

现在,我希望在GA.py中运行
main
时检查这些条件。我在
foocross
中引入了一个假前提条件,只是为了测试合同是否被检查,但似乎没有。如何确保检查合同

下面是我的代码的一小部分:

# GA.py
def main():
    # some code
    crossover.foocross(params)
    # some more code

if __name__ == "__main__":
    main()

#crossover.py
def injectionco(p1, p2, chrom):
    """
        pre:
            isinstance(p1, int) # this should raise an error. p1 is never an int
            isinstance(p2, list)
            isinstance(chrom, int)
            forall(p1, lambda elem: any(isinstance(elem, i.__class__) for i in p2))
            forall(p2, lambda elem: any(isinstance(elem, i.__class__) for i in p1))
            len(p1) == len(p2)

        post:
            p1 is __old__.p1
            p2 is __old__.p2
            p1 == __old__.p1
            p2 == __old__.p2
            isinstance(__return__, p1.__class__)    # returns an individual
            len(__return__) == len(p1)
            id(__return__) not in [id(p1), id(p2)]
            forall(__return__, lambda elem: __return__.count(elem) == 1)
        """

    #code
    return #something
PS:这对我来说是一个非常难写的问题,因为我必须去掉很多代码(因为框架非常复杂),而且我还不熟悉按合同设计。所以,如果我错过了一些有助于回答这个问题的信息,请提问,我很乐意提供更多信息:)

看着,你需要做的似乎就是:

# this needs to be there unconditionally.
import contract
contract.checkmod(__name__)

if __name__ == '__main__':
   import doctest, GA
   doctest.testmod(GA)
但是,下面的将不起作用(因为在
导入GA
中,
contract.checkmod()
不会发生):


还有另一个解决办法。对于大型代码库,编辑多个文件以启用/禁用每个模块的契约检查将非常繁琐。我可以从我的主模块调用所有合同检查,如下所示:

#GA.py

import crossover # and all other required modules
import contract

for mod in [crossover]: # put all other imported modules in that list
    contract.checkmod(mod)
#GA.py

import crossover # and all other required modules
import contract

for mod in [crossover]: # put all other imported modules in that list
    contract.checkmod(mod)