Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

312
Views
How do I define a function at runtime in python?

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 ?

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!