[英]How to define signature of a callable argument?
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? 声明
bar(..)
接受两个int并返回一个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. 通过
typing
Callable
类型,可以指定参数类型和可调用值的返回类型。
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. 请注意,由于Python是动态类型的,因此在某种程度上,类型提示只是文档。 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. 但是,可以将
mypy
等第三方工具用于静态类型分析,以帮助确保您的代码不会传递错误类型的值。
Python is dynamically typed which means the interpreter type checks as the code runs, and the type can change over time. Python是动态类型的,这意味着解释器的类型会在代码运行时进行检查,并且该类型会随着时间而变化。
PEP 484 introduced type hints. PEP 484引入了类型提示。 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.