[pytest-dev] Question about fixtures and the use of finalizers vs yield

Dr Keith M Franklin keith.franklin at gmail.com
Mon Dec 4 06:49:24 EST 2017


Good morning/afternoon,

I hope this is the right place to post this.  I’ve been using PyTest for a while but recently come across someone else’s fixture which made me wonder if I’m doing this right.  Basically I’ve been creating a fixture like and adding a finalizer like so:

@pytest.fixture(scope=‘function’)
def my_fixture(request):
  # Code that does something e.g. creates a database record
  rec = DBObject()

  def clean_up():
      # Code required to clean up the fixture code and return the state back to the
      ...
  request.addfinalizer(clean_up)
  return rec


However, I’ve seen fixtures written using yield instead e.g.


@pytest.fixture(scope=‘function’)
def my_fixture(request):
  # Code that does something e.g. creates a database record
  rec = DBObject()
  yield rec

  # Code required to clean up the fixture code and return the state back to the
  ...

Can I ask, is there any real difference between the two approaches?  Is there a preferred method and if so why?

Thanks in advance for any help.

Keith


More information about the pytest-dev mailing list