Let's say I have a function that accepts a callable
def foo(bar):
print(bar(1, 2))
What is the best way to declare that bar(..)
accepts two ints and returns a str? Is there a more well-defined way than just documentation?
The Callable
type from typing
lets you specify both the argument types and the return type of a callable value.
from typing import Callable
def foo(bar: Callable[[int,int],str]):
print(bar(1, 2))
Note that since Python is dynamically typed, a type hint is, to some extent, just documentation. Third-party tools like mypy
, though, can be used for static type analysis to help ensure that your code doesn't pass a value of the wrong type.
Python is dynamically typed which means the interpreter type checks as the code runs, and the type can change over time.
PEP 484 introduced type hints. You can do this by the following syntax:
def bar( a: int, b: int) -> str:
return
def foo(bar: callable) -> None:
print(bar(1, 2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.