Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Escriba una función con un invocable

Tengo muchas funciones que tienen la misma firma, digamos (int, int) -> int .

¿Hay alguna manera de escribir estas funciones con un Callable (o algo más) para evitar especificar los tipos de parámetros y el tipo de devolución para cada una de estas funciones? Me gustaría hacer algo así (pero obviamente falla):

 from typing import Callable f: Callable[[int, int], int] def f(x, y): # with the previous line, this is equivalent to 'def f(x: int, y: int) -> int:' ...

Ejecutar mypy da como resultado:

 file.py:4: error: Name "f" already defined on line 3 Found 1 error in 1 file (checked 1 source file)
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Tal vez haya una solución más elegante. No se recomienda, pero puede configurar <function>.__annotations__ . Más info al respecto aquí .

 from typing import get_type_hints callable_int_annotations = {"x": int, "y": int, "return": int} def f_with_hint(x: int, y: int) -> int: return x + y def f_without_hint(x, y): return x + y print(f"Before {get_type_hints(f_with_hint)=}") print(f"Before {get_type_hints(f_without_hint)=}") f_without_hint.__annotations__ = callable_int_annotations print(f"After {get_type_hints(f_with_hint)=}") print(f"After {get_type_hints(f_without_hint)=}")
 Before get_type_hints(f_with_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>} Before get_type_hints(f_without_hint)={} After get_type_hints(f_with_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>} After get_type_hints(f_without_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda