Home > database >  How can i add a function / method to the annotation of another function / list in Python?
How can i add a function / method to the annotation of another function / list in Python?

Time:07-15

If i want to specify the signature of a function or content of a list, i can just use these annotations:

def say(word: str):
    print(f"I said {word}!")

some_words: list[str] = ["foo", "bar"]

But what if i want to use functions and methods in annotations? I`ve searched for this everywhere but didn't find anything similar to it. Here is the example of what i want to reach:

def add(a: int, b: int) -> int:
    return a   b

def run_with_notify(func: <what type?>, *args):
    print("Start!")
    print(func(*args))
    print("End!")

run_with_notify(add, 2, 3)

Of course i could just not use annotations at all, but it is much more convenient to use them if you work in powerful IDE. Any ideas?

CodePudding user response:

you can use from typing library like this:

from typing import Callable
def run_with_notify(func: Callable, *args):
    print("Start!")
    print(func(*args))
    print("End!")
  • Related