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.
|
|
“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.