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

168
Views
Type a function with a callable

I have a lot of functions that have the same signature, let's say (int, int) -> int.

Is there a way to type these functions with a Callable (or something else) to avoid specifying the types of the parameters and the return type for each of these functions? I would like to do something like that (but it obviously fails):

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:'
    ...

Running mypy results in:

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 answers
Answer question

0

Maybe there's a more elegant solution. Not recommended but you can set the <function>.__annotations__. More info about it here.

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 Report
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!