Lucas Emanuel
Lucas Emanuel

Reputation: 626

I wanted to understand what this yield does

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/

Upvotes: 3

Views: 1200

Answers (1)

Tawfiq Khalilieh
Tawfiq Khalilieh

Reputation: 23

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

Upvotes: 1

Related Questions