Similar to the third bullet-point mentioned by Anoop, but a bit more thorough and based on an answer from a different post: https://stackoverflow.com/a/45304063
You can do the following, using a pytest fixture:
@pytest.fixture()
def mod_fixture():
import sys
del sys.modules['mod']
import mod
return mod
Subsequently, use in your tests as such:
def test_set_x(mod_fixture):
mod_fixture.global_setter()
assert mod_fixture.x == 123
def test_get_x(mod_fixture):
with pytest.raises(NameError):
mod_fixture.global_getter()
This will ensure that you get a fresh mod module with a clean state each time the fixture is used. If you like, you can change the scope of the fixture such that it doesn't necessarily reset per function, but per module: https://docs.pytest.org/en/6.2.x/fixture.html#fixture-scopes