Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type hint a function that returns a function? [duplicate]

Let's say I have the following code:

def validator(blacklist: list=['heck', 'muffins']):

    def f(questionable_word: str) -> bool:
        return questionable_word in blacklist

    return f

validator_british = validator(['pish'])
validator_british('pish')  # returns True
validator_british('heck')  # returns False

My question is how do I type-hint the validator function such that it indicates a function is returned, and specifically a function that takes a str and returns a bool? The f function's signature is:

def f(questionable_word: str) -> bool

What do I put in the ??? place for validator?

validator(blacklist: list=['heck', 'muffins']) -> ???:
like image 273
Nathaniel Ford Avatar asked Mar 09 '17 21:03

Nathaniel Ford


People also ask

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

from typing import Callable def my_function(func: Callable): Note: Callable on its own is equivalent to Callable[..., Any] . Such a Callable takes any number and type of arguments ( ... ) and returns a value of any type ( Any ).

What are type hints PyCharm?

Type hinting in PyCharm Last modified: 24 February 2022. PyCharm provides various means to assist inspecting and checking the types of the objects in your script. PyCharm supports type hinting in function annotations and type comments using the typing module and the format defined by PEP 484.

How do you Typehint a function in Python?

Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5. The name: str syntax indicates the name argument should be of type str . The -> syntax indicates the greet() function will return a string.

How do you specify multiple return types in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax.


1 Answers

typing.Callable is what you want:

validator(blacklist: list=['heck', 'muffins']) -> Callable[[str], bool]:
like image 153
Moses Koledoye Avatar answered Sep 19 '22 07:09

Moses Koledoye