Let's consider the following code
class CommonDependency:
...
@app.on_event("startup")
async def start():
parser = ArgumentParser(...)
... # here dep are init with command line arguments
return dep
@app.get("/")
async def root(dep = Depends(start)):
... # here dep is needed
return ...
The start function needs to be run at startup because it will make use of command line arguments in order to create the dependencies.
The problem is that dep is some stateful object that should share its state across all requests since boot.
The solution is declare dep in the module scope
dep = CommonDependency(...)
@app.on_event("startup")
async def start():
dep.property = ... # here the property contains the init dependency that we need
and overwrite a property declared inside the class to be accessed through all the module functions.
However, doing that, Depends became useless because the dep object is visible by all functions.
I really don't like this approach, is there any better solution?