出现问题的原因:
我们都知道,Python 3中函数的类型是function
,而我现在想要将一个函数作为参数传入另一个函数中,我的第一反应就是将function
作为函数的默认值来传入。比较离谱的是VSCode的语法自动高亮机制依然给我高亮了……你亮啥啊该亮的时候不亮,不该亮的时候锃亮。
错误位置:def extract_number_from_prediction(predict_function:function,question:str,prediction:str):
报错信息:NameError: name 'function' is not defined
出错原因是Python 3就没有内置function
这个类……
解决方案:
改用typing.Callable
或者collections.abc.Callable
(3.9 +)对象。(函数的抽象类)
typing.Callable:https://docs.python.org/3/library/typing.html#typing.Callable
collections.abc.Callable:https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable
先引入包:from typing import Union, Callable
Callable[[str], Union[int,float]]
表示输入是str,输出是int或float的函数。
原代码改成:def extract_number_from_prediction(predict_function:Callable[[str], Union[int,float]],question:str,prediction:str):
参考资料:Python 3: “NameError: name ‘function’ is not defined” - Stack Overflow