3

I wanted to understand what this yield does. In the examples I find, I always see this type of code, but I don't understand what it differs from a normal instance

def get_db():
  db = SessionLocal()
  try:
    yield db
  finally:
    db.close()

This example is in the FastAPI documentation: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/

Lucas Emanuel
  • 470
  • 2
  • 10
  • 2
    Does this answer your question? [What does the "yield" keyword do?](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) – Yogesh Thambidurai Jul 29 '22 at 21:51
  • I've seen several examples using arrays, but it's not the case with this code, I don't understand what this yield is doing, it's just a database session – Lucas Emanuel Jul 29 '22 at 21:53
  • As written this isn't good code. Any chance there was a `@contextlib` line right before it? – tdelaney Jul 29 '22 at 22:00
  • Is your question really about the `yield`, or is it about the `try/finally` part? – John Gordon Jul 29 '22 at 22:03
  • This is an example from the FastAPI documentation, which you can view here: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/ My question is about yield – Lucas Emanuel Jul 29 '22 at 22:03
  • 2
    That example does `async def get_db():` - that `async` part makes sense. But the page you reference has a pretty long explanation of why you do it. By doing a `yield` inside a `try`, the code guarantees that the `finally` clause (which closes the database) is always run, even if there is an exception. – tdelaney Jul 29 '22 at 22:08
  • 1
    `yield` allows the dependency to run extra code after the request has finished, for example to do some extra clean up such as closing any lingering database connections that are no longer needed (as in the given example) or removing temporary files. – MatsLindh Jul 29 '22 at 22:20
  • 1
    This is a `context manager`(a term of Python) implementation that helps you to close automatically the connection right before exiting from the context. – ishak O. Jul 29 '22 at 22:39

1 Answers1

1

yield is a keyword that is used like return, except the function will return a generator.

quick example:

def fun(num):
    for i in range(num):
        yield i
x = fun(5)
print(x)
# <generator object create_generator at 0xb7555c34>
for object in x:
    print(object)

"""
expected output:
        0
        1
        2
        3
        4
"""

you can checkout [this link][1] to read more


  [1]: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do

in your example, the code is trying to return the db as an object and if it fails it closes it

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 04 '22 at 13:28