Skip to content

Generators

Sometimes we want to call something before and after original function call.

That purpouse can be reached by using yield keyword.

A database dependency with yield

For example, you could use this to create a database session and close it after finishing.

Only the code prior yield statement is executed before sending a response

1
2
3
4
def dependency():
    db = DBSession()
    yield db
    db.close()

The yielded value is what is injected into original function

1
2
3
4
def dependency():
    db = DBSession()
    yield db
    db.close()

The code following the yield statement is executed after the original function has been called

1
2
3
4
def dependency():
    db = DBSession()
    yield db
    db.close()

Tip

As same as a regular depends behavior you can use async and sync declarations both with an async original function and only sync declaration with a sync one.

Warning

All errors occurs at original function or another dependencies will be raised this place

1
2
3
4
def dependency():
    db = DBSession()
    yield db
    db.close()
To guarantee db.close() execution use the following code:
1
2
3
4
5
6
def dependency():
    db = DBSession()
    try:
        yield db
    finally:
        db.close()