Referencing `self` in `__old__` in PyContract constraints

跟風遠走 提交于 2019-12-25 02:19:37

问题


I'm working on writing some constraints for a class method using PyContract (not PyContracts). As a postcondition, I'd like to ensure that the memory address of the instance hasn't changed i.e. id(self) should be the same before and after calling the function. How can I do this with PyContract? I have the following (minimal) code:

class Individual:
    def append(self, chrom):
        """
            post:
                __old__.self is self
                len(__old__.self.chromosomes)+1 == len(self.chromosomes)
                self.chromosomes[-1] == chrom
        """
        self.chromosomes.append(chrom)

The problem with the constraints here is that in post, I get this error: _holder instance has no attribute 'self'

The interesting thing here is that class Individual has an __init__ whose constraints look like this:

pre:
    isinstance(chromosomes, list)
post[chromosomes]:
    __old__.chromosomes is chromosomes
    __old__.chromosomes == chromosomes
post:
    hasattr(self, 'chromosomes')
    self.chromosomes == chromosomes

As far as I can tell, PyContract doesn't like that I call __old__.self. How do I get around this?


回答1:


This seems to fix it:

class Individual:
    def append(self, chrom):
        """
            post[self]:
                __old__.self is self
                len(__old__.self.chromosomes)+1 == len(self.chromosomes)
                self.chromosomes[-1] == chrom
        """
        self.chromosomes.append(chrom)

source



来源:https://stackoverflow.com/questions/13021011/referencing-self-in-old-in-pycontract-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!