我使用赋值表达式(也称为walrus运算符,在佩普572中定义)来定义T类型。这似乎是一个优雅的解决方案,但显然我不同意。
关于下列代码:
# Python 3.10.4
from collections.abc import Sequence
from typing import TypeVar
def foo(seq: Sequence[T := TypeVar('T')]) -> T:
return seq[0]填报报告:
error: Invalid type comment or annotation
error: Name "T" is not defined海象被TypeVar禁止了吗?
发布于 2022-06-21 10:25:42
这是,的坏主意。
假设您将来导入了注释--那么这只是一个长字符串,不会发生赋值。假设您想要函数体中的cast(T, something)。如果mypy接受这一点,它将错过运行时错误:
NameError:未定义名称"T“
因此,在这种情况下,PEP563会改变代码的行为。
from __future__ import annotations
from collections.abc import Sequence
from typing import TypeVar
def foo(seq: Sequence[T := TypeVar('T')]) -> T:
return cast(T, seq[0])您可以选择cast('T', ...),但这并不是真正的注释--仅限于这种情况。
发布于 2022-08-03 14:36:54
从python3.12开始(假设PEP695被接受),可以使用更优雅和功能更强大的语法来替换TypeVar
from typing import Callable
def func[**P, R](cb: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R:
...https://stackoverflow.com/questions/72697728
复制相似问题