【发布时间】:2021-03-18 19:28:29
【问题描述】:
我想根据预定义类型定义函数签名(参数和返回类型)。
假设我有这种类型:
safeSyntaxReadType = Callable[[tk.Tk, Notebook, str], Optional[dict]]
这意味着 safeSyntaxReadType 是一个接收 3 个参数(来自上面列出的类型)的函数,它可以返回 dict 或者可能不返回任何内容。
现在假设我使用了一个函数safeReadJsonFile,其签名是:
def safeReadJsonFile(root = None, notebook = None, path = ''):
我想将类型safeSyntaxReadType分配给签名中的函数safeReadJsonFile,可能是这样的:
def safeReadJsonFile:safeSyntaxReadType(root = None, notebook = None, path = ''):
但是这种语法不起作用。这种类型分配的正确语法是什么?
我可以这样做:
def safeReadJsonFile(root:tk.Tk = None, notebook:Notebook = None, path:str = '') -> Optional[dict]:
但我想避免这种情况。
读了很多(所有的typing docs,和一些PEP544)后,我发现没有这样的语法可以轻松地将类型分配给定义中的整个函数(最接近的是@typing.overload和这不是我们在这里所需要的)。
但作为一种可能的解决方法,我实现了一个装饰器函数,它可以帮助轻松分配类型:
def func_type(function_type):
def decorator(function):
def typed_function(*args, **kwargs):
return function(*args, **kwargs)
typed_function: function_type # type assign
return typed_function
return decorator
用法是:
greet_person_type = Callable[[str, int], str]
def greet_person(name, age):
return "Hello, " + name + " !\nYou're " + str(age) + " years old!"
greet_person = func_type(greet_person_type)(greet_person)
greet_person(10, 10) # WHALA! typeerror as expected in `name`: Expected type 'str', got 'int' instead
现在,我需要帮助:由于某种原因,类型检查器 (pycharm) 不会提示输入,如果使用应该是等效的修饰语法:
@func_type(greet_person_type)
def greet_person(name, age):
return "Hello, " + name + " !\nYou're " + str(age) + " years old!"
greet_person(10, 10) # no type error. why?
我认为装饰样式不起作用,因为装饰不会更改原始函数greet_person,因此返回的装饰函数的键入不会影响原始greet_person函数时的输入。
如何使修饰的解决方案发挥作用?
【问题讨论】:
-
我认为你不能定义一个函数。如果您正在传递一个函数,您可以使用您的新类型作为提示,例如作为另一个函数的参数。另外,
dict or None正确吗?我一直使用Optional[dict],但也许or是一种更新的语法? -
我不是 python 打字专家。但在打字稿中,这是为函数分配类型的方式,对于
dict or None,这在 pycharm 中对我有用,所以我很好 -
对于
dict or None的东西,在重新检查后我发现如果你在函数签名中定义它是有效的,但是如果你在Callable中使用它,例如它会返回任何...所以Optional[dict]可能是正确的语法 -
@EliavLouski 您可以为此使用 Mypy 包。
标签: python python-typing