Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

310
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda