Eli*_*ski 3 python python-typing
我想根据预定义的类型定义一个函数签名(参数和返回类型)。
假设我有这种类型:
safeSyntaxReadType = Callable[[tk.Tk, Notebook, str], Optional[dict]]
Run Code Online (Sandbox Code Playgroud)
这意味着safeSyntaxReadType是一个接收 3 个参数(来自上面列出的类型)的函数,它可以返回一个dict或可能不返回任何内容。
现在假设我使用一个函数,safeReadJsonFile其签名是:
def safeReadJsonFile(root = None, notebook = None, path = ''):
Run Code Online (Sandbox Code Playgroud)
我想将类型分配给签名中safeSyntaxReadType的函数safeReadJsonFile,可能类似于:
def safeReadJsonFile:safeSyntaxReadType(root = None, notebook = None, path = ''):
Run Code Online (Sandbox Code Playgroud)
但是这种语法不起作用。这种类型分配的正确语法是什么?
我可以这样做:
def safeReadJsonFile(root:tk.Tk = None, notebook:Notebook = None, path:str = '') -> Optional[dict]:
Run Code Online (Sandbox Code Playgroud)
但我想避免这种情况。
在阅读了很多(所有打字文档和一些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
Run Code Online (Sandbox Code Playgroud)
用法是:
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
Run Code Online (Sandbox Code Playgroud)
现在,我需要帮助:由于某种原因,如果使用应该是等效的装饰语法,类型检查器 (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?
Run Code Online (Sandbox Code Playgroud)
我认为装饰风格不起作用,因为装饰不会改变原始功能,greet_person因此在输入原始功能时,返回的装饰功能的输入不会影响greet_person。
我怎样才能使装饰的解决方案起作用?
只需将函数分配给代表特定可调用类型的新名称。
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)
Run Code Online (Sandbox Code Playgroud)
请记住,定义为对象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
Run Code Online (Sandbox Code Playgroud)
这也编码了只有与复制签名兼容的函数才是有效目标。
# 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'
Run Code Online (Sandbox Code Playgroud)