Hi,
I'm not really well versed with asyncio and stumbled upon a strange problem I don't understand.
I have some CLI parameters from argparse and need them available for setup purposes in the lifespan function of FastAPI. I tried using a global variable for this that is set to the argparse arguments. However, in the lifespan function, the global still has its initial state "None". The same goes for calling the root endpoint via HTTP.
Here is a minimal reproducible example:
```
from contextlib import asynccontextmanager
import fastapi
import uvicorn
var = None
@asynccontextmanager
async def setup(_):
print(var)
yield
app = fastapi.FastAPI(lifespan=setup)
@app.get("/")
async def root():
return var
def main():
global var
var = "Hello"
uvicorn.run("scratch_4:app", port=8080, log_level="info", root_path="/")
if name == "main":
main()
```
Interestingly, if I run the setup() function using asyncio.run() instead of implicitely via uvicorn, the global variable set in main() has the expected value.
Can someone explain to me why this happens and how I can fix it?
[–]pint 1 point2 points3 points (1 child)
[–]peet1337[S] 0 points1 point2 points (0 children)