Home > OS >  Using global variables in pytest
Using global variables in pytest

Time:12-21

I am trying to write a test as follows and an ending up getting the following error:

def test_retry():
  hits = 0

  def f():
    global hits
    hits  = 1
    1 / 0

  with pytest.raises(ZeroDivisionError):
    f()

and get the following error:

>       hits  = 1
E       NameError: name 'hits' is not defined

but am curious why this code doesn't work. Does pytest somehow alter the global variables?

I know this can be solved using a list like hits = [0], but i'm trying to understand why the code doesn't work.

I've also tried using pytest_configure, and that works too.

CodePudding user response:

Use nonlocal instead. hits is not a global variable.

nonlocal hits
  • Related