1
from fastapi import Depends, FastAPI

class MyDependency:
    def __init__(self):
        # Perform initialization logic here
        pass

    def some_method(self):
        # Perform some operation
        pass

def get_dependency():
    # Create and return an instance of the dependency
    return MyDependency()

app = FastAPI()

@app.get("/example")
def example(dependency: MyDependency = Depends(get_dependency)):
    dependency.some_method()

For the code snippet above, does subsequent visits to /example create a new instance of the MyDependency object each time? If so, how can I avoid that?

Chris
  • 18,724
  • 6
  • 46
  • 80
Michael Xia
  • 190
  • 8

1 Answers1

2

Yes, each request will receive a new instance.

If you don't want that to happen, use a cache decorator, such as the built-in lru_cache in functools: - it's just a regular function, so any decorators will still be invoked (since they replace the original function with a new one which wraps the old one):

from functools import lru_cache

...

@lru_cache
def get_dependency():
    # Create and return an instance of the dependency
    return MyDependency()

However, if you use the same dependency multiple places in the hiearchy (for the same request), the same value will be re-used.

If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • Alternatively, one could [use a `lifespan` handler to instantiate the object and share it between requests](https://stackoverflow.com/a/76322910/17865804) – Chris Jun 10 '23 at 16:13