Using global variables in pytest

Question:

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.

Asked By: rakshith91

||

Answers:

Use nonlocal instead. hits is not a global variable.

nonlocal hits
Answered By: Unmitigated
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.