Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Did Python 3.9 update how to type hint the function type?

Before 3.9 I would have used this:

from typing import Callable

def my_function(argument_function: Callable) -> None:

Now I am not sure anymore.

PEP 585 has a list of deprecated Typing-types that does not include typing.Callable but does include collections.abc.Callable. So far I haven't use the collections.abs module but I wonder if typing.Callable might be related to collections.abc.Callable therefore making the Callable type hint deprecated, too.

I did try this:

def my_function(argument_function: callable) -> None:

And it works.

But is that really the correct way now? Or Do I still have to import typing.Callable?

like image 856
jfl21 Avatar asked Dec 21 '25 07:12

jfl21


1 Answers

Since there isn't an answer, I'm elevating juanpa.arrivillaga's comment to an answer. Quoting the above comment [sic]:

you probably should be using the fll form, Callable[[ArgTypes], ReturnType]

Or fleshing it out:

from typing import Callable

# Let's say this was an example of argument_function and that's 
# the signature that you expect in my_function

def foo(x: int) -> str:
    return str(x)

def my_function(argument_function: Callable[[int], str]) -> None:
    pass
like image 129
Zephaniah Grunschlag Avatar answered Dec 24 '25 10:12

Zephaniah Grunschlag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!