[英]Is there a standard way to specify the type of a callback function in a docstring?
I have a function which accepts a callback. 我有一个接受回调的函数。 Is there a standard way to document the type of this parameter?
是否有标准方法来记录此参数的类型?
def example(callback):
"""Example function.
Parameters
----------
callback : type
Description of `callback`.
"""
print(callback(3, 14))
Found the answer while formulating the question, but the question itself doesn't give any results on Google. 在制定问题的同时找到了答案,但问题本身并未在Google上给出任何结果。
PEP-0484 introduces type annotation in python. PEP-0484在python中引入了类型注释。 For example the type of a callback function taking two integers and returning a string is:
例如,采用两个整数并返回字符串的回调函数的类型是:
from typing import Callable
Callable[[int, int], str]
I needed something like that and while I think that callback should always be a function, AFAIK there's no way to specify the type of a function and I kept reusing callbacks with the same arguments doing different things so that's what I came up with. 我需要类似的东西,虽然我认为回调应该始终是一个函数,AFAIK没有办法指定一个函数的类型,我不断重复使用相同的参数执行不同的回调,这就是我想出的。
import abc
class BaseCallback(metaclass=abc.ABCMeta):
def __init__(self, param: int):
self.param = param
self.do_things()
@abc.abstractmethod
def do_things(self) -> int:
raise NotImplementedError
class MyCallback(BaseCallback):
def do_things(self):
return self.param * 2
def func(callback: BaseCallback): # type of callback specified
callback()
func(callback=MyCallback)
You don't need to run the do_things
method in init (imo it's ugly), depends on how much power do you have regarding where/when callback is run. 你不需要在init中运行
do_things
方法(这很难看),取决于你在回调运行的时间/地点有多少功率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.