What type hint can I use in Python if my type is a function?

Scott Leonard

I want to use type hints in Python, but there are certain cases where the type of my parameters are not clear to me... do functions have a type, or are they a special case. I would like to do something like the following:

pseudocode:

def run_function(function_to_run: fn):
  function_to_run(data)

is this possible? If so, what type should I use?

edit: I was hoping to distinguish a function from other callables such as classes... but maybe that doesn't matter and is overly cautious.

hiro protagonist

as mentioned in the documentation: you can use Callable.

you could for example use it this way:

from typing import Callable

def run_function(function_to_run: Callable[[int], str]):
    function_to_run(data)

if function_to_run is a function from int to str.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

In Python 3.5, how can I specify a function as a type hint?

What is the type hint for a function

What type of RAM can I use to upgrade my system?

What type can I use for an Image in my class

Should I import a model only to use type hint in Python?

How can I type-hint a nested object in Python?

How can I type hint an attribute in Python 3.5?

How can I type-hint a function where the return type depends on the input type of an argument?

What is the return type hint of a generator function?

What is the type hint of a function that returns an image?

What type hint to use if return value is mixed?

What's the type hint for "can be converted to" mean?

How do I type hint a filename in a function?

How to hint the type of a function I do not control?

How should I use the Optional type hint?

What is the type hint for a (any) python module?

What is the best generic type hint for a dataclass in python?

How can I hint that a type is comparable with typing

type hint clone function in python 3.5+

What should be the return type of my Power BI function if I want to use it as axis value for my report

How do I hint to Couchbase schema-inference to use my "type" field?

How can I create a type hint that my returned list contains strings?

How can I specify the function type in my type hints?

In Swift, can I use function type in tuple?

How can I use function type?

Generic type hint python

In TypeScript, when invoking a function, why can I hint that a null argument has some other type?

What is the correct type hint to use when exporting a pydantic model as a dict?

How do I type-hint that a Python function returns instance of any class derived from a superclass?