You can use the typing module for Callable annotations.

The Callable annotation is supplied a list of argument types and a return type:

from typing import Callable

def func_b(func: Callable[[int], int]) -> int:
    return func(3)
Answer from Alex on Stack Overflow
🌐
Python
peps.python.org › pep-3107
PEP 3107 – Function Annotations | peps.python.org
Function annotations, both for parameters and return values, are completely optional. Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
Usage is in the form Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]. Concatenate is currently only valid when used as the first argument to a Callable. The last parameter to Concatenate must be a ParamSpec or ellipsis (...). For example, ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › function-annotations-python
Function Annotations in Python - GeeksforGeeks
May 10, 2019 - Purpose of function annotations: The benefits from function annotations can only be reaped via third party libraries. The type of benefits depends upon the type of the library, for example · Python supports dynamic typing and hence no module is provided for type checking. Annotations like · [def foo(a:”int”, b:”float”=5.0) -> ”int”] (syntax described in detail in the next section) can be used to collect information about the type of the parameters and the return type of the function to keep track of the type change occurring in the function.
Top answer
1 of 13
101

Function annotations are what you make of them.

They can be used for documentation:

def kinetic_energy(mass: 'in kilograms', velocity: 'in meters per second'):
     ...

They can be used for pre-condition checking:

def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        msg = 'Var: {0}\tValue: {1}\tTest: {2.__name__}'.format(var, value, test)
        assert test(value), msg


def is_int(x):
    return isinstance(x, int)

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    return _between

def f(x: between(3, 10), y: is_int):
    validate(f, locals())
    print(x, y)


>>> f(0, 31.1)
Traceback (most recent call last):
   ... 
AssertionError: Var: y  Value: 31.1 Test: is_int

Also see http://www.python.org/dev/peps/pep-0362/ for a way to implement type checking.

2 of 13
96

I think this is actually great.

Coming from an academic background, I can tell you that annotations have proved themselves invaluable for enabling smart static analyzers for languages like Java. For instance, you could define semantics like state restrictions, threads that are allowed to access, architecture limitations, etc., and there are quite a few tools that can then read these and process them to provide assurances beyond what you get from the compilers. You could even write things that check preconditions/postconditions.

I feel something like this is especially needed in Python because of its weaker typing, but there were really no constructs that made this straightforward and part of the official syntax.

There are other uses for annotations beyond assurance. I can see how I could apply my Java-based tools to Python. For instance, I have a tool that lets you assign special warnings to methods, and gives you indications when you call them that you should read their documentation (E.g., imagine you have a method that must not be invoked with a negative value, but it's not intuitive from the name). With annotations, I could technically write something like this for Python. Similarly, a tool that organizes methods in a large class based on tags can be written if there is an official syntax.

🌐
Tutorialspoint
tutorialspoint.com › home › python › python function annotations
Python Function Annotations
February 21, 2009 - The function in Python is also an object, and one of its attributes is __annotations__. You can check with dir() function. ... This will print the list of myfunction object containing __annotations__ as one of the attributes.
🌐
Medium
medium.com › @bengiese22 › python-function-annotations-the-amazing-feature-not-a-lot-of-python-developers-know-about-1ef6489fe8c5
Python Function Annotations — The amazing feature not a lot of Python Developers know about! | by Benjamin Giese | Medium
January 29, 2022 - Python Function Annotations are exactly what they sound like, annotations for your functions. These annotations come in two types, parameter annotations and return type annotations. One large benefit is that they can provide much needed explanation to the reader as to what type a function parameter expects or a function returns.
🌐
LogRocket
blog.logrocket.com › home › understanding type annotation in python
Understanding type annotation in Python - LogRocket Blog
June 4, 2024 - The parameter can be annotated as follows: from typing import Union def show_type(num: Union[str, int]) -> None: ... Not all parameters in a function are required; some are optional.
Find elsewhere
🌐
Javatpoint
javatpoint.com › function-annotations-in-python
Function Annotations in Python - Javatpoint
Function Annotations in Python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
GitHub
github.com › python › typing › discussions › 1163
How to annotate modifications for function arguments with `ParamSpec` and `TypeVar` · python/typing · Discussion #1163
But their remote counterparts should have as signature that allows the original types or a wrapper ObjectRef[OriginalType] for each argument: do_things.remote(x: int | ObjectRef[int], y: float | ObjectRef[float]) -> ObjectRef[float]: ... do_more_things.remote(name: str | ObjectRef[str], value: float | ObjectRef[float]) -> ObjectRef[str]: ... Now, I know type annotating this in this particular API design is probably difficult, and possibly not easily supported.
Author   python
🌐
Real Python
realpython.com › ref › glossary › function-annotation
function annotation | Python Glossary – Real Python
A way to attach type information or type hints to function arguments and return values.
🌐
Runestone Academy
runestone.academy › ns › books › published › fopp › Functions › TypeAnnotations.html
12.7. Type Annotations — Foundations of Python Programming
A type annotation, sometimes called a type hint, is an optional notation that specifies the type of a parameter or function result. It tells the programmer using the function what kind of data to pass to the function, and what kind of data to expect when the function returns a value.
🌐
Real Python
realpython.com › lessons › annotations
Annotations (Video) – Real Python
00:42 Now this may seem as a bit of a review, annotation style is the same as you did for the type hints before. To do function annotations, you annotate the arguments and the return value.
Published   October 29, 2019
🌐
Python
typing.python.org › en › latest › spec › annotations.html
Type annotations — typing documentation
In its basic form, type hinting is used by filling function annotation slots with classes: def greeting(name: str) -> str: return 'Hello ' + name · This states that the expected type of the name argument is str. Analogically, the expected return type is str. Expressions whose type is assignable to a specific argument type are also accepted for that argument.
🌐
University of Toronto
teach.cs.toronto.edu › ~csc148h › notes › python-recap › type_annotations.html
1.5 Python Type Annotations — CSC148 Course Notes
Annotating the methods of a class is the same as annotating any other function, with two notable exceptions: By convention, we do not annotate the first parameter self. Its type is always understood to be the class that this method belongs to. Sometimes we need to refer to the class itself, because it is the type of some other parameter or the return type of a method. Because of a quirk of Python, we can only do so by including a special import statement at the very top of our Python file.
🌐
Accuweb
accuweb.cloud › home › what are function annotations in python?
What are Function Annotations in Python? - AccuWeb Cloud
September 5, 2023 - Excess parameters such as *args and **kwargs enable passing an arbitrary number of arguments in a function call. The annotation syntax for these parameters is outlined below. def foobar(*args: expression, **kwargs: expression): In Python 2.x, nested parameters involve passing a tuple in a function ...
🌐
Medium
medium.com › geekculture › python-type-annotation-for-functions-and-class-2e8e3148e376
Python — Type Annotation for Functions and Class | by Tony | Geek Culture | Medium
June 21, 2022 - To annotate the type for a function, you need to type annotate each formal parameter, and at the same time annotate the return value of the function.
🌐
Datagrok
datagrok.ai › concepts › functions › function annotations
Function annotations | Datagrok
When you create a function, script, or query that results in a table, you can annotate it with the meta.searchPattern tag. This tag will be used to call the function with the specified parameters within the sentence. The searchPattern tag can be any sentence that contains placeholders for the ...