【问题标题】:How to define a type for a function (arguments and return type) with a predefined type?如何为具有预定义类型的函数(参数和返回类型)定义类型?
【发布时间】: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


【解决方案1】:

只需将函数分配给代表特定可调用类型的新名称。

Greetable = Callable[[str, int], str]

def any_greet_person(name, age):
    ...

typed_greet_person: Greetable = any_greet_person

reveal_type(any_greet_person)
reveal_type(typed_greet_person)

请记住,定义为any_greet_person的对象是特定类型的,创建后不能简单地删除它。


为了创建具有特定类型的可调用对象,可以从模板对象复制它(抽象类型Callable 和Protocol 不适用于Type[C])。这可以通过装饰器来完成:

from typing import TypeVar, Callable

C = TypeVar('C', bound=Callable)  # parameterize over all callables

def copy_signature(template: C) -> Callable[[C], C]:
    """Decorator to copy the static signature between functions"""
    def apply_signature(target: C) -> C:
        # copy runtime inspectable metadata as well
        target.__annotations__ = template.__annotations__
        return target
    return apply_signature

这也编码了只有与复制的签名兼容的函数才是有效的目标。

# signature template
def greetable(name: str, age: int) -> str: ...

@copy_signature(greetable)
def any_greet_person(name, age): ...

@copy_signature(greetable)  # error: Argument 1 has incompatible type ...
def not_greet_person(age, bar): ...

print(any_greet_person.__annotations__)  # {'name': <class 'str'>, 'age': <class 'int'>, 'return': <class 'str'>}
if TYPE_CHECKING:
    reveal_type(any_greet_person) # note: Revealed type is 'def (name: builtins.str, age: builtins.int) -> builtins.str'

【讨论】:

  • @EliavLouski 这两种方法中的哪一种?什么 PyCharm 版本?
  • PyCharm 2020.3.2(社区版),使用装饰器的方法。 print(any_greet_person.__annotations__) 确实在运行时打印正确的类型,但没有静态类型提示 [see](![image](user-images.githubusercontent.com/47307889/…)
  • @EliavLouski 抱歉,PyCharms 内置类型检查器似乎不如 e.g.我的派。 PyCharm“正确地”知道函数的类型是应用了装饰器的裸定义——它似乎还没有弄清楚这会影响签名。您可能想使用不同的类型检查器进行验证(如上所述,MyPy 有效)或使用 IntelliJ 打开票证。
  • 在为 Pycharm 安装 Mypy 插件并为当前解释器安装 mypy 后,会使 pycharm 报告 mypy 错误!请编辑您的答案以包含此@MisterMiyagi,然后我将接受此答案!
  • Jetbrains 对其问题跟踪器上的问题非常敏感。他们可能会很快解决这一切,就像它被张贴在那里一样(如果尚未修复)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多