Search code examples
pythonpytestfixturespytest-fixtures

pytest: Fixture shortcut to object inside another fixture breaks when object is updated


I have code that is essentially like this where the fixture foo is a shortcut to the foo object inside fixture myclass. This is purely for convenience so I don't have to do myclass.foo, however when myclass.foo gets updated, the foo fixture is not, even though they seem to be the same object before it's updated. Is this just a bad practice I should avoid?

class MyClass:
    def __init__(self):
        self.foo = object()

    def update_foo(self):
        self.foo = object()

@pytest.fixture
def myclass():
    yield MyClass()

@pytest.fixture
def foo(myclass):
    return myclass.foo

def test_foo(myclass, foo):
    assert myclass.foo is foo
    myclass.update_foo()
    assert myclass.foo is foo  # <-- this one fails

Solution

  • It is because immutability, a value cannot be changed after it has been created and every reference will point to the same value until you explicitly reassign the variable name.

    it is not related to pytest but to python itself

    you can read more about it here