As I’m currently using and learning PyTest framework in my QA Automation project, I have noticed that a lot of functions decorated with @pytest.fixture() decorator use the yield keyword instead of the return keyword. I was not sure about the exact difference between these two statements, therefore I have decided to research it a bit more.

return vs yield statement

Both yield and return are keywords in Python and both are used in a function to pass values from one function to another in a program.

Return statement returns a single value or an object. This is executed only once and any code following the return keyword is not executed.

Yield statement, on the other hand, returns a generator object (something I will have to look up as well, since my current understanding of generator object is not good). Anyway, among many differences between the two, the most important difference I have currently noticed is that the yield statement does not stop the execution and the program continues. This allows for a “clean up” (as I will show in my simple example below).

Example from my project

For my test cases I have setup a conftest.py file containing main fixtures shared between all test cases with the first fixture being the driver function, which initializes the main driver.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import pytest

@pytest.fixture()
def driver():
    options = Options()
    options.add_argument('-headless')
    driver = webdriver.Firefox(options=options)
    driver.implicitly_wait(1)
    driver.get('https://www.automationexercise.com/')

    assert driver.title == 'Automation Exercise'
		
	# Here is the yield driver statement
    yield driver
    
	# Because of the yield statement, we are able to clean up afterwards by quitting the driver
    driver.quit()

“Yielding” the driver allows to quit the driver afterwards. I have tested it with the return statement and as expected, the driver.quit() was never executed as the program stopped at the return statement.

This is probably not the most important difference between the two, but I will take a look into the generator objects next.