简体   繁体   English

如何定义可调用参数的签名?

[英]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.

相关问题 如何将可调用对象定义到另一个 python 类中 - How to define a callable object into another python class 如何定义只能调用一次的可调用对象? - How to define a callable that can only be called once? 如何在Python文档字符串中定义“可调用”参数? - How to define a “callable” parameter in a Python docstring? 如何定义带参数的变量? - How to define a variable with an argument? 如何使用任意参数列表 (vararg) 键入可调用对象 - How to typehint a callable with arbitrary argument list (vararg) 如何获得可调用对象的签名参数,或者可靠地确定何时无法实现? - How to get the signature parameters of a callable, or reliably determine when this is not possible? 如何使用可选参数和参数解包来定义方法? - How to define method with optional argument and argument unpacking? 如何定义与具有可变参数的函数相对应的“可调用”类型? - How do I define a “Callable” type that corresponds to a function with variable arguments? 如何将命名关键字参数添加到函数签名 - How to add a named keyword argument to a function signature 如何在 a..class:: 签名中包含一个元组作为默认参数? - How to include a tuple in a ..class :: signature as default argument?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM