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']) -> ???:
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 ).
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.
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.
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.
typing.Callable
is what you want:
validator(blacklist: list=['heck', 'muffins']) -> Callable[[str], bool]:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With