Frage

This is a follow up of my previous question

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 some object hasn't changed i.e. id(myObj) should be the same before and after calling the function. How can I do this with PyContract?

Here's what I'm doing right now:

def foo(param1, param2)
    """
        # some other constraints
        post[param1, param2]:
            __old__.param1 is param1
            __old__.param2 is param2
    """

However, that postcondition fails. I can only imagine that this is because __old__.param1 is not stored in the same memory location as is param1. This makes sense, as PyContract needs to make a copy of param1 before foo is executed in order to check its value against the value of param1 after foo is done executing.

Assuming that the above analysis is true, it only serves to explain why id(__old__.param1) is different from id(param1). However, it still doesn't answer how I can ensure that id(param1) doesn't change as a side-effect of foo. How could I go about checking this in PyContract?

War es hilfreich?

Lösung

I am not familiar with the PyContract library you are using, but the actual contract you are testing for does not make much sense in Python since function arguments are passed by reference. If you have code like the following:

x = a
y = b
foo(x, y)

Then the function will receive references to the objects named by x and y in the calling scope. Inside the function call, you have two separate variables initialised with references to those arguments.

So changes to those variables inside the function can not affect the binding of x and y in the calling scope.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top