I would like to define a function at runtime, without the use of eval or exec.
Here's what I want:
from typing import Callable, Dict
def create_function(params: Dict) -> Callable:
func = None
# Here the code to create func ...
return func
params = {
"id": {
"type": int,
"default": None
},
"name": {
"type": str,
"default": None
},
"kind": {
"type": str,
"default": None
}
}
my_func = create_function(params)
# my_func would have this signature: my_func(id: int = None, name: str = None, kind: str = None)
The reason I want to create functions at runtime is for FastApi. In FastApi, you use a function as a dependency to have query parameters in your routes. I want to use that feature but the query parameters are defined at runtime, not when I'm writing the code.
Here's a minimal example with functions parameters written in the code directly:
from typing import Optional
from fastapi import FastAPI, Depends, Query
app = FastAPI()
def query_parameters(id: int = Query(None), name: str = Query(None)):
return {"id": id, "name": name}
@app.get("/hello")
async def get(query_parameters=Depends(query_parameters)):
return {"message": "hello"}
All I want to do is to define query_parameters dynamically.
Any ideas ?